2

I have nginx configured to serve a single page React.js app as static content. react-router handles routing in browser.

To make it possible for users to enter all urls (not just the domain example.com, but also urls like example.com/some/path, example.com/some/other/path, etc.) directly in the address bar, I am doing,

error_page 404 /index.html

This works perfectly fine everywhere except in Internet Explorer. IE shows 404 page for this.

How do I configure nginx, such that it serves index.html, if the request path cannot be matched to a file in the root directory.

Thanks.

  • Is it possible that IE showing you cached version? – alexus Apr 28 '16 at 19:39
5

This is a job for try_files.

try_files $uri /index.html;

$uri will load any static resources if they are present and accessible; for any inaccessible URLs, /index.html will be served (with a 200).

  • Which one would be better approach try_files or error_page 404 =200 /index.html as mentioned by Alex_hha below? and why? Thanks – Mir Nazim Apr 29 '16 at 6:38
  • 1
    The end result is probably the same, but nobody really expects error_page to be used in that manner, so it will be confusing to anyone else who looks at it; while try_files is well understood and intended to be used this way. – Michael Hampton Apr 29 '16 at 6:42
  • Also, one day you would want to send 404 (e.g. for unknown image) and with error_page “hack” you'll get big problem… – Alexey Ten Apr 29 '16 at 7:46
0

As workaround you can use

server {
    listen       80;
    server_name  www.example.net;

    root /vhosts/default/public_html;

    error_page 404 =200 /index.html;

    location / {
        index index.html;
    }
}

Is it possible that IE showing you cached version?

it seems default behavior for IE. At least for IE11 on Windows 7

P.S. It turns out that your index.html MUST be 512+ bytes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.