Search code examples
javascriptreactjsnginxmod-rewritecreate-react-app

Serve React application as sub path in nginx


There is a React App which is serve on 0.0.0.0:5000 locally. Also i have a domain name example.com.

What I want to do is proxy the example.com/app directory into the 0.0.0.0:5000.

I tried following way.

location /app  {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_redirect     off;
    proxy_set_header   Host $host;
    rewrite /app/(.*) /$1 break;
    proxy_pass http://0.0.0.0:5000/app;

}

But in the console errors shows like bellow

Loading failed for the <script> with source “http://localhost/static/js/bundle.js”. app:45:1
Loading failed for the <script> with source “http://localhost/static/js/0.chunk.js”. app:45:1
Loading failed for the <script> with source “http://localhost/static/js/main.chunk.js”.

Also I tried to add homepage: './app to the package.json too

How do I fix it ?


Solution

  • The nginx config looks ok to me, but you will need to update the webpack config as well as the router configuration within the React app in order to serve the application on a particular path.

    I can't take any credit for the following gist, but it covers all the cases you should need:

    https://gist.github.com/codepunkt/ae82a0f3b9deb93908dc1f3d5bbc8da2

    (Note that your basePath should begin with a "/", such as "/app")