: O. Yuanying

Rails3.1@Unicorn で nginx の設定

Rails3.1 のアプリケーションを Unicorn で動かして、静的ファイルは nginx におまかせ! ってしようとした時に nginx の設定で少しはまったのでメモ。

前提

  • nginx を 127.0.0.1:80 で動かしている。
  • Unicorn を 127.0.0.1:8080 で動かしている。
  • Rails3.1 の assets を 事前に rake assets:precompile してある。

nginx の設定

  • /assets ディレクトリ以下のファイルを expire max で永久にブラウザ側にキャッシュさせる。
    • assets 内のファイルは内容が変わればファイル名も変わるため、永久にキャッシュさせておーけー。
  • try_files で すでに存在する静的ファイルはすべて nginx で処理。
upstream apps-server {
    server 127.0.0.1:8080;
}

server {
    listen  80;
    server_name     app.example.com;
    
    root /path/to/app/current/public;
    error_log /path/to/app/current/log/error.log;

    location ~* ^/assets {
            expires max;
            add_header Cache-Control public;
            break;
    }

    try_files /system/maintenance.html $uri $uri/index.html $uri.html @unicorn;

    location @unicorn {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_pass http://apps-server;
    }
}