Last time, I deployed a React.js project on a server.

But I found the router doesn’t work. I click the menu to other child pages. It always returns a 404 page.

I did some search and found the reason. When I try to get a page by url, nginx would try to find the page file under the root folder. But for a built React.js SPA app, all routers are written in the index file other than single pages. So we need to redirect the requests to index.html.

Here is what you should add to your nginx conf file:

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

The whole block of conf on my server looks like this:

http {
    include       mime.types;
    default_type  application/octet-stream;


    sendfile        on;

    keepalive_timeout  65;

    server {
        listen   80;
        server_name  localhost;

        location / {
            root   /home/ease/build;    # the path of your project's build directory
            index  index.html index.htm;
            try_files $uri /index.html; 
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

} 

Reload nginx config. It should works now.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *