How to configure non-80 port forwarding in Nginx server

2023-11-09 14:42:51

<p>Nginx can be conveniently configured as a reverse proxy server:</p><p>  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 &quot;nginx&quot;;   }  }</p><p>However, if nginx&#39;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&#39;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:</p><p>Add nginx virtual host</p><p><img src="https://freeonlinedomain.com/uploads/allimg/Server/20231109/1fdqdqa1nac515.jpg" width="323" height="403" border="0" vspace="0" title="" alt="" style="width: 323px; height: 403px;"/></p><p>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).</p><p>Nginx does non-80-port forwarding. To forward, you can use nginx&#39;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:</p><p>server { server_name &nbsp;www.test.com listen 80; &nbsp;location / { proxy_pass http://127.0.0.1:8080; }}</p><p>Yes, it&#39;s that simple. This is the core of configuring port forwarding.</p><p>However, when you encounter a business that needs to obtain the real ip, you need to add the configuration about the real ip:</p><p>server { server_name &nbsp;www.test.com listen 80; &nbsp;location / { proxy_pass http://127.0.0.1:8080; &nbsp;proxy_set_header host $host:80; &nbsp;proxy_set_header x-real-ip $remote_addr; &nbsp;proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; }}</p><p>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.</p>


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