How to configure non-80 port forwarding in Nginx server

11-09-2023

Nginx can be conveniently configured as a reverse proxy server:

  server {  listen 80;   server_name localhost;   location / {  proxy_pass http://x.x.x.x:9500;   proxy_set_header host $host:80;   proxy_set_header x-real-ip $remote_addr;   proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;   proxy_set_header via "nginx";   }  }

However, if nginx's listening port is not the default 80 port, change it to another port such as 81 port. The request.getserverport () in the back-end server can't get the correct port, and it still returns 80; In response.sendredirect (), the client may not get the correct redirect url. The correct configuration method is as follows:

Add nginx virtual host

To forward nginx, of course, nginx must be configured. Nginx can be enhanced by adding virtual host configuration. First, look at the configuration file of nginx. My nginx file is in/etc /etc/nginx/nginx.conf As can be seen from the above figure, nginx finally introduced the configuration file in the directory VHOSTS. D. Then create a file with the suffix. conf in the /etc/nginx/vhosts.d directory (if the directory does not exist, you need to create it yourself).

Nginx does non-80-port forwarding. To forward, you can use nginx's proxy_pass configuration item. Nginx listens on port 80, and after receiving the request, it will forward it to the url to be forwarded. The specific configuration is as follows:

server { server_name  www.test.com listen 80;  location / { proxy_pass http://127.0.0.1:8080; }}

Yes, it's that simple. This is the core of configuring port forwarding.

However, when you encounter a business that needs to obtain the real ip, you need to add the configuration about the real ip:

server { server_name  www.test.com listen 80;  location / { proxy_pass http://127.0.0.1:8080;  proxy_set_header host $host:80;  proxy_set_header x-real-ip $remote_addr;  proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; }}

The configuration of proxy_set_header is to change the request header of http. And host is the host name of the request, x-real-ip is the real ip of the request, and x-forwarded-for indicates who initiated the request.

Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us