I'm having issues getting my reverse proxy to work when using a path in nginx. What I am trying to do is have one address for an application, and dictate the environment with the path. Depending on the path, it would point to a different server. I'm able to get the reverse proxy working when using a direct link, but using a path is getting a 404 error.
app.foo.bar/dev = 404 error
devapp.foo.bar = success
What have I done wrong on app.foo.bar/dev ?
Here is the reverse proxy setup that is working, but I'd rather not use:
server {
listen 80; # DEV Application Proxy
server_name devapp.foo.bar;
location / {
proxy_pass http://appserver.foo.bar:7010;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://appserver.foo.bar:7010/ /;
proxy_connect_timeout 300;
}
}
Here is a portion of what I am wanting to do by using path, but getting 404 error.
# APP Environment Proxy
server {
listen 80;
server_name app.foo.bar;
location /dev {
proxy_pass http://appserver.foo.bar:7010;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://appserver.foo.bar:7010 /;
proxy_connect_timeout 300;
}
}
I've googled this type of setup, but I'm not able find a solution. Thanks in advance for the any assistance.
Best Answer
When you have
proxy_pass http://appserver.foo.bar:7010;
, nginx appends the normalized URI to the request URL passed to backend.So, when you request
http://app.foo.bar/dev
, the request goes tohttp://appserver.foo.bar:7010/dev
. If your dev server doesn't have this path, then it will return 404, which nginx returns to the client.If you want all requests starting with
http://app.foo.bar/dev
to go tohttp://appserver.foo.bar:7010
such that all rest of the URI is added to the backend server URI, then you can use this configuration:So, we capture the part after
/dev
with regex to a variable, and then we add that variable to end ofproxy_pass
path.