oranie's blog

旧:iをgに変えると・・・なんだっけ・・・

nginx 1.7系である条件を元にアクセスログの出力を抑制する場合の設定

nginx 1.7系を設定している時に、まあ良くある要望でリバースプロキシの設定をしたいんだけど、アプリ側が静的ファイルを返す時にそれはアクセスログに出したく無いって設定でハマった。
初めはlocationの内部でif文書いてaccess_log offとかでやろうとすると、何故かファイル自体へのアクセスがそもそも404になる。で、じゃあ画像用のlocation切ってやろうとすると、locationの条件に正規表現を使った場合は

nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in

こんなエラーになってしまう。

じゃあどうすれば良いかと言うと1.7系ではaccess_logディレクティブに

The if parameter (1.7.0) enables conditional logging. A request will not be logged if the condition evaluates to “0” or an empty string. In the following example, the requests with response codes 2xx and 3xx will not be logged:

    map $status $loggable {
        ~^[23]  0;
        default 1;
    }

    access_log /path/to/access.log combined if=$loggable;

The following parameters configure logging to syslog:

というのが追加されていて、
http://nginx.org/en/docs/http/ngx_http_log_module.html
以下の様な設定を入れる事で設定出来た。

    map $uri $loggable {
        ~.*\.(gif|jpg|png|ico|js|css)$ 0;
        default 1;
    }
    access_log  /var/log/nginx/access.log  ltsv if=$loggable;

そもそも前のエラーになる場合の設定ミスをまだ深く追えていないので行き当たりばったり感たっぷりのメモでした。