Search code examples
reactjsnginxwebserverurl-routingnginx-reverse-proxy

Creating a URL mapping for my ReactJS app running in development mode


I have a ReactJS app running on development mode, on port number 3000. I am trying to create a mapping with Nginx so that all requests at avt1.example.com/demo gets routed to http://localhost:3000/demo but this just does not work and all I see is a blank page.

But if I try avt1.example.com:3000/demo, it works as expected. I cannot understand where am I going wrong. Here is the configuration file I created for Nginx and example.com

    server {
        listen 80;
        server_name avt1.example.com www.avt1.example.com;
        location /demo {
                # pass to ReactJS app
                proxy_pass http://localhost:3000;
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        location / {
                # pass to NodeJS app
                proxy_pass http://localhost:3001;
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

What is it that I am missing or doing incorrectly? I started the react-app using yarn start and works just fine if I provide the port number with the domain.

Also, if there is a suggestion of running the ReactJS app in a better way, please let me know.


Solution

  • Your question is missing the node js code, so i guess you set up the "demo" url as well in the nodejs code there. So you need to edit you site-enable config to the following

    server {
            listen 80;
            server_name avt1.example.com www.avt1.example.com;
            location /demo {
                    # pass to ReactJS app
                    proxy_pass http://localhost:3000/demo;
                    proxy_set_header Host $host;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            }
            location / {
                    # pass to NodeJS app
                    proxy_pass http://localhost:3001;
                    proxy_set_header Host $host;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            }
    }
    

    but the better readable would be

    # pass to ReactJS app
    upstream demotool {
        server 0.0.0.0:3000/demo;
    }
    
    server {
            listen 80;
            server_name avt1.example.com www.avt1.example.com;
            location /demo {
                    proxy_pass demotool;
                    proxy_set_header Host $host;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            }
    }
    

    i don't the a reason to proxy pass the backend stuff right now