2012-11-12 77 views
1

當給定的路徑不存在時,是否可以告訴nginx一個替代位置?我想從我的Rails應用程序提供靜態資產,但是有時編譯的資產可能不可用,我希望有一個回退。nginx緩存未命中行爲

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; 
    } 

UPDATE: 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; 
    } 

回答

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,...選項)

注意/替代URI可以是一個命名的位置(具有例如關於try_files

更新的指令將網址傳遞到Rails應用程序)

看到http://nginx.org/en/docs/http/ngx_http_core_module.html#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(這是try_files指令的@cache部分)
  3. 我˚F我們得到的@cache位置,它會首先檢查代理緩存區one的比賽
  4. 如果沒有緩存找到匹配將在http://127.0.0.1:81
+0

是啊,感謝反向代理請求到Rails應用程序。我已經提出了這個問題,請看看它是否有意義。它應該是服務器作爲靜態內容,從緩存或最後的手段是真正的Rails應用程序。 – Tombart

+0

更新了我的答案,以反映發佈的配置 – cobaco

+0

謝謝!現在它終於似乎工作 – Tombart