当给定路径不存在时,是否可以告诉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;
}
答案 0 :(得分:1)
是的,使用try files指令:
# 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
}
这将尝试请求的网址,如果没有找到,请尝试替代uri(您还可以添加第3个,第4个,...选项)
注意/ alternative uri可以是一个命名位置(例如,用于将url传递给rails应用程序的指令)
有关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 "";
}
换言之,对于所有部分以/assets/
开头的网址:
$uri
指令的try_files
部分)@cache
指令的try_files
部分)@cache
位置,它将首先检查代理缓存区one
是否匹配http://127.0.0.1:81