tkuchikiの日記

新ブログ https://blog.tkuchiki.net

Nginx で query string を見て動的にファイルを配信する

server {
    listen 80;
    server_name localhost;

    rewrite_log on;
    error_log /var/log/nginx/rewrite.log notice;

    location ~ ^/weather+\.json {
        rewrite ^ /weather/$arg_date.json;
    }

    location  ~ ^/weather/.*\.json {
        default_type application/json;
        root /var/www/html;
        try_files $uri =404;
        error_page 404 = @info;
    }

    location @info {
        more_set_headers -s 404 "Cache-Control: no-cache, no-store";
        return 404 " ";
    }
}

という設定ファイルで、

$ cat /var/www/html/weather/20141001.json
{"weather":"sunny"}

を置いている状態で、http request を送ると、

$ curl -s "http://localhost/weather.json?date=20141001"
{"weather":"sunny"}

$ curl -I "http://localhost/weather.json?date=20141001"
HTTP/1.1 200 OK
Server: ngx_openresty/1.4.3.6
Date: Fri, 10 Oct 2014 07:25:05 GMT
Content-Type: application/json
Content-Length: 20
Last-Modified: Fri, 10 Oct 2014 07:02:02 GMT
Connection: keep-alive
ETag: "5437846a-14"
Accept-Ranges: bytes

のようになります。
以下は、rewrite log です。

2014/10/10 16:08:03 [notice] 21659#0: *1 "^" matches "/weather.json", client: 127.0.0.1, server: localhost, request: "GET /weather.json?date=20141001 HTTP/1.1", host: "localhost"
2014/10/10 16:08:03 [notice] 21659#0: *1 rewritten data: "/weather/20141001.json", args: "date=20141001", client: 127.0.0.1, server: localhost, request: "GET /weather.json?date=20141001 HTTP/1.1", host: "localhost"

ファイルが存在しない場合は以下のように 404 を返すことが確認できます。

$ curl -I "htp://localhost/weather.json?date=20141002"
HTTP/1.1 404 Not Found
Server: ngx_openresty/1.4.3.6
Date: Fri, 10 Oct 2014 07:25:32 GMT
Content-Type: application/octet-stream
Content-Length: 1
Connection: keep-alive
Cache-Control: no-cache, no-store