Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send all requests to index.html except certain extensions

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.

like image 385
vinczemarton Avatar asked Mar 01 '26 05:03

vinczemarton


1 Answers

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)$ { 
}
like image 149
Richard Smith Avatar answered Mar 03 '26 20:03

Richard Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!