upstream app {
server localhost:3000;
}
server {
...
# If I comment this location out, images are displayed on the website
location ~* \.(?:jpg|jpeg|png|gif|swf|xml|txt|css|js)$ {
expires 6004800;
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}
...
location /app {
alias /path/to/app/public/;
try_files $uri $uri @app;
}
location @app {
rewrite /app(.*) $1 break;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $proxy_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://app;
proxy_redirect http://app/ /app/;
}
...
}
I'm struggling with this for some time. I have an express app in a sub folder under nginx. Above is the code in my nginx file in /sites-available/. When I remove the location for the static files, the images and css of the app are proxied, but if the static files cache is in the nginx file then the images and css files of the express app are not displayed on the website.
Could someone help, please?
Regex locations have precedence over prefixed location blocks in nginx request processing. Hereinafter are relevant excerpts of nginx's location directive documentation.
I strongly encourage you to read them carefully as many people don't do it and miss the basics.
A few examples before to understand keywords :
location /toto { [...] }
location ~ /toto { [...] }
A few other examples to illustrate the two operators that modifies location lookup order :
location ^~ /toto { [...] }
: prefixed location with higher priority than regex locationslocation = /toto { [...] }
: exact prefixed location (exact match, highest priority)To sum things up, the priority list during location election for incoming request URI is :
location = /too
location ^~ /toto
location ~ /toto
location /toto
So the cleaner way to solve your issue is using :