I need some help with nginx config for SPA. I made mine from pieces I managed to google, but I don't understand how it works.
What I need:
1) Serve static files
location ~ \.(css|js|svg|woff|woff2|ico|ttf|eot|jpe?g|png|txt)$ {
try_files $uri $uri/ =404;
expires 1y;
add_header Cache-Control "public";
}
If the file is not found I return 404. That's ok if I just type incorrect file name in URL, but if I type incorrect file name in my index.html instead of 404 page I get a blank page. Is that supposed to be this way?
2) Requests to /api need to be redirected to Node backend
location /api {
try_files '' @proxy;
}
location @proxy {
proxy_pass http://localhost:3000;
}
I'm not really sure in this line, if it's supposed to look this way
try_files '' @proxy;
3) And the biggest problem, requests that do not match anything need to return index.html
location / {
try_files '' /index.html;
expires -1;
}
location = /index.html {
expires -1;
}
As far as I understand first block redirects all unknown requests to index.html, but I don't understand how the second block serves this index.html. I do not write to serve this file, there is no try_files directive.
1) Serve static files
Your solution is perfectly fine. It is only needed if you require to set different cache control and expiry headers for these URIs. The try_files statement is unnecessary as that's the same as the default behaviour.
2) Requests to /api need to be redirected to Node backend
Your solution can be simplified to:
location /api {
proxy_pass http://localhost:3000;
}
This will process any URI that begins with /api unless it matches the regular expression in step (1). You can avoid that by using the ^~ operator. See this document for details.
3) And the biggest problem, requests that do not match anything need to return index.html
This is usually implemented as:
location / {
try_files $uri $uri/ /index.html;
...
}
Unless the request matches any other location, or a file, or directory, the URI will be internally rewritten to /index.html. See this document for details.