NGINX allows you to forward requests from one server to another. Typically, it is used to forward requests from reverse proxy to web server. Many times it is also used to redirect URLs in case your domain has changed or moved. But sometimes you may need to forward request to another port in NGINX. In this article, we will learn how to do this.
How to Forward Request to Another Port in NGINX
Let us say you want to redirect request http://example.com/product/abc to http://example.com:9000/abc. In this case you can add a location block to your NGINX server configuration.
location /product { proxy_pass http://127.0.0.1:9000/; }
In the above code, we create a location block for URLs starting with /route. Please remember to add forward slash after port number 9000 as shown above.
The above location block will redirect request to different port on same server. If you want to redirect request to a different port on another server (e.g., 54.43.32.21), replace 127.0.0.1 with that port number.
location /product { proxy_pass http://54.43.32.21:9000; }
If you want to redirect request http://example.com/product/abc to http://example.com:9000/product/abc then add the following location block. In this case, do not add forward slash after port number as shown below.
location /product { proxy_pass http://127.0.0.1:9000; }
Alternatively, you can also use the following configuration which is more detailed and offers more customization. For example, this one allows you to preserve host name while the above ones do not.
location /route/ { proxy_pass http://127.0.0.1:9000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
In each of the above examples, if you face any issues, try using ‘location /route/’ instead of ‘location /route’ and vice versa.
In this article, we have learnt a couple of simple ways to redirect request to another port in same NGINX server.
Also read:
How to Check if Key Exists in Python Dictionary
How to Get Random Numbers Between Two Numbers in JS
NGINX Catch All Location
How to Download Images in Python
How to Remove Trailing Newline in Python