1

与えられたパスが存在しないときにどこを見るべきかをnginxに伝えることは可能ですか?Railsアプリケーションから静的アセットを提供したいのですが、コンパイルされたアセットが利用できない場合があり、フォールバックが必要です。

Production.rb

  # Disable Rails's static asset server (Apache or nginx will already do this)
  config.serve_static_assets = false

nginx.conf:

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

更新: nginx.conf

  #cache server
  server {
        listen 80;

        # serving compressed assets
        location ~ ^/(assets)/  {
                root /var/app/current/public;
                gzip_static on; # to serve pre-gzipped version
                expires max;
                add_header Cache-Control public;
                add_header ETag "";
        }

        try_files $uri /maintenance.html @cache;

        location @cache {
            proxy_redirect off;
            proxy_pass_header Cookie;
            proxy_ignore_headers Set-Cookie;
            proxy_hide_header Set-Cookie;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_cache one;
            proxy_cache_key app$request_uri;
            proxy_cache_valid 200 302  5s;
            proxy_cache_valid 404      1m;
            proxy_pass http://127.0.0.1:81;
        }
  }

  #real rails backend
  server {
        listen 81;
        root /var/app/current/public;
        error_log /var/app/current/log/error.log;

        rails_env production;
        passenger_enabled on;
        passenger_use_global_queue on;
  }
4

1 に答える 1

1

はい、ファイルの試行ディレクティブを使用します。

# note: you don't need the overhead of regexes for this location
location /assets/ {
   try_files $uri /alternative_to_try
   # ... add back in rest of your assetts config
}

これは要求されたURLを試し、見つからない場合は別のURIを試します(3番目、4番目、...オプションを追加することもできます)

/ Alternative uriは名前付きの場所にすることができることに注意してください(たとえば、URLをrailsアプリに渡すためのディレクティブを使用)

詳細とに関するいくつかの例については、http://nginx.org/en/docs/http/ngx_http_core_module.html#try_filesを参照してください。try_files

アップデート:

アセットの場所を次のように変更します

location /assets/  {
   try_files $uri @cache;
   root /var/app/current/public;
   gzip_static on; # to serve pre-gzipped version
   expires max;
   add_header Cache-Control public;
   add_header ETag "";
}

言い換えれば、部分が次で始まるすべてのURLに対して/assets/

  1. パスに対応する実際のファイルがあるかどうかを確認します(これはディレクティブの$uri一部です)try_files
  2. そうでない場合は、指定された場所@cacheにリクエストを渡します(これはディレクティブの@cache一部です)try_files
  3. その@cache場所に到着すると、最初にプロキシキャッシュゾーンoneに一致するものがないかチェックします
  4. 一致するキャッシュが見つからない場合は、リクエストをRailsアプリにリバースプロキシします。http://127.0.0.1:81
于 2012-11-12T15:06:34.930 に答える