Is it possible to tell nginx an alternative location where to look when given path does not exist? I’d like to serve static assets from my Rails application, however sometimes the compiled asset might not be available and I’d like to have a fallback.
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;
}
yes with the try files directive:
this will try the requested url and if not found try the alternative uri (you can also add a 3th, 4th, … option)
Note that /alternative uri can be a named location (with for instance the directives for passing the url to the rails app)
see http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files for more details and some examples regarding
try_filesupdate:
right so change your assets’ location to
in other words for all url’s where the part starts with
/assets/:$uripart of thetry_filesdirective)@cachepart of thetry_filesdirective)@cachelocation, it will first check the proxy cache zoneonefor a matchhttp://127.0.0.1:81