Home >Operation and Maintenance >Nginx >How to configure port forwarding of non-80 ports in Nginx server
nginx can be easily 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"; } }
But if the listening port of nginx is not the default port 80, change it to another port such as port 81.
The request.getserverport() in the backend server cannot obtain the correct port, and the returned value is still 80;
When responding.sendredirect(), the client may not be able to obtain the correct redirect url.
Let’s look at the correct configuration method in detail:
Add nginx virtual host
Do nginx For forwarding, of course nginx needs to be configured. The functionality of nginx can be enhanced by adding virtual host configuration. First, take a look at the nginx configuration file. The author's nginx file is in /etc/nginx/nginx.conf. As you can see from the picture above, nginx introduces the configuration file in the vhosts.d directory at the end. Then you need to create a file with the .conf suffix 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 to 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 encountering a business that needs to obtain a real IP, you also need to add 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; } }
proxy_set_header This configuration is to change the http request header. 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.
The above is the detailed content of How to configure port forwarding of non-80 ports in Nginx server. For more information, please follow other related articles on the PHP Chinese website!