0

I'm trying to do a simple reverse proxy to my local react app with nginx. I can't wrap my head around how this works. Do i need a root variable in location /test or maybe a alias? because nginx is looking in the wrong address. (im running my react app locally at localhost:3001)

Already tried using rewrite /test(.*) /$1 break in the "location /test"-block

this is my nginx.conf:

server {
    listen 81 ;
    server_name app1.localhost;

    location / {  
        root   html;
        index  index.html index.htm;
    }
    location /test {
        proxy_pass   http://localhost:3001;
    }
}

heres the console log when i try to enter app1.localhost:81/test: enter image description here

6
  • Why do you have two location blocks (or, asking differently, why don't you put the proxy_pass into the / location block)? Commented Oct 25, 2021 at 11:17
  • this is just an experiment, I want / to just show the default index.html file from nginx and /test to show my react app Commented Oct 25, 2021 at 11:27
  • The issue is that your react app is unaware of the fact that is it mounted under the /test base path. So you see requests being made like /static/js/… which actually would need to be /test/static/js/… in order to resolve correctly. Commented Oct 25, 2021 at 11:39
  • Hmm, so the static files of my react app have to be hosted from nginx too? Commented Oct 25, 2021 at 11:43
  • It'd be easiest if you'd just choose a specific server_name for your app exclusively and put the proxy_pass under /. You can still have the default nginx site. Commented Oct 25, 2021 at 11:45

1 Answer 1

3

Just go with two server blocks:

server {
    listen 81 default_server;

    location / {  
        root html;
        index index.html index.htm;
    }
}

server {
    listen 81;
    server_name app1.localhost;

    location / {  
        proxy_pass http://localhost:3001;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

That does work, but why cant I use the same server for both of the locations?
location /test means "everything that starts with /test". But your app includes links like /static/js/… that don't start with /test… You'd basically need to have your app run at localhost:3001/test to make this work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.