How does Nginx do port forwarding?
How does Nginx do port forwarding? I believe most people haven't learned this skill yet. In order for everyone to learn it, I summarized the following contents for everyone. Without saying much, let's look down together.
First introduce the most commonly used, forwarding the domain name to another local port
server{ listen 80; server_name tomcat.shaochenfeng.com; index index.php index.html index.htm; location / { proxy_pass http://127.0.0.1:8080; #forwarding rules proxy_set_header Host $proxy_host; #Modify the forwarding request header so that applications on port 8080 can receive real requests proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }}
This way, when visiting http://tomcat.shaochenfeng.com, it will be forwarded to the local port 8080
Forward domain name to another domain name server{ listen 80; server_name baidu.shaochenfeng.com; index index.php index.html index.htm; location / { proxy_pass http://www.baidu.com; proxy_set_header Host $proxy_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }}
This way, when you visit http://baidu.shaochenfeng.com, it will be forwarded to http://www.baidu.com
Local forwarding of one port to another port or another domain name server{ listen 80; server_name 127.0.0.1; #public ip index.php index.html index.htm; location / { proxy_pass http://127.0.0.1:8080; #or http://www.baidu.com proxy_set_header Host $proxy_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }}
This way, when visiting http://127.0.0.1, it will be forwarded to the local port 8080 or http://www.baidu.com
With/without/
When configuring proxy_pass proxy forwarding, if url followed by/, it indicates absolute root path; if there is no/, it indicates relative path
for example
Plus/
server_name shaochenfeng.comlocation /data/ {proxy_pass http://127.0.0.1/;}
Visit http://shaochenfeng.com/data/index.html will be forwarded to http://127.0.0.1/index.html
The requested URL/data/ {proxy_pass http://127.0.0.1;} was not found on this server.
About using Nginx to do port forwarding methods to share here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you like this post, share it with more people.