3

I'm using nginx to serve my react app and it serves me well in redirecting everything except static files to index.html with the following:

location / {
  try_files $uri /index.html =404;
}

I was content with this for some time but noticed that when certain image and javascript files are not available on the server, the index.html gets served instead. This itself is not a problem.

However when a cache layer is added before the app it caches all these results since they do have 200 as status code.

What I want is to serve static files and redirect other requests to index.html when they do not end in certain extensions (.js, .css, .png, .jpg, .gif etc...)

For example

http://example.com/some/path -> /index.html
http://example.com/existing-file.doc -> /existing-file.doc
http://example.com/some/non-existing-image.png -> 404 error

So addresses like http://example.com/main.1234.js returns the js file if it exists, a 404 response otherwise, never index.html

Should I make a regular expression block, like:

location ~ \.js$|\.css$|\.png$|\.jpg$ {
    what do I write here?
}

I'm not entirely sure how to best approach this.

vinczemarton
  • 7,756
  • 6
  • 54
  • 86

1 Answers1

2

It's perfectly valid to leave the block empty, and it will inherit the value for root and index from the surrounding block. The default action for an empty location block is similar to try_files $uri $uri/ =404;

You may also want to simplify your regular expression, for example:

location ~ \.(js|css|png|jpg)$ { 
}
Richard Smith
  • 45,711
  • 6
  • 82
  • 81