djulb
djulb

Reputation: 395

NGINX: Rewrite url and reverse proxy to a different port

I am having difficulty rewriting url and reverse proxy the request to a spring boot app. Rewrite works but i am losing port number and cause of that it is not working. For example localhost:80/order.pl converts into localhost/home. The port gets lost and app is not receiving the request
Similar examples online don't work.

server
{
    listen 80;
    server_name localhost;
    set $upstream localhost:8050;

    location ~"^\/order.pl$"
    {
        rewrite "^\/order.pl$ "/home" permanent;
    }

    location /
    {
        proxy_set_header X - Forwarded - For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header X - Real - IP $remote_addr;
        proxy_buffering off;
        proxy_connect_timeout 30;
        proxy_send_timeout 30;
        proxy_read_timeout 30;
        proxy_pass http: //$upstream;
    }
}

If I don't do rewrite, reverse proxy is working but with rewrite I am losing port number. Any info would be appreciated.

Thanks

Upvotes: 2

Views: 8308

Answers (1)

Richard Smith
Richard Smith

Reputation: 49672

Nginx would not normally specify the port as part of an external redirect if the port number is the same as the default port for the scheme. Port 80 for http and port 443 for https.

You can specify the port explicitly in the rewrite statement.

For example:

location = /order.pl {
    return 301 $scheme://$host:$server_port/home;
}

Note: I used curl to test this, as the browser dropped the port from the address-bar for exactly the same reasons.

Upvotes: 1

Related Questions