有时我们的应用不想让他们直接监听80端口、这时就需要用到端口转发

本文中,我们介绍Nginx如何做端口转发,还有各种转发规则

将域名转发到本地端口

首先介绍最常用的,将域名转发到本地一个端口上

1
2
3
4
5
6
7
8
9
10
11
12
server{
listen 80;
server_name liuxiangyang.space;
index index.php index.html index.htm;

location / {
proxy_pass http://127.0.0.1:8080; # 转发规则
proxy_set_header Host $proxy_host; # 修改转发请求头,让8080端口的应用可以受到真实的请求
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

这样访问http://liuxiangyang.space 时就会转发到本地的8080端口

将域名转发到另一个域名

1
2
3
4
5
6
7
8
9
10
11
12
server{
listen 80;
server_name baidu.liuxiangyang.space;
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;
}
}

这样访问http://baidu.liuxiangyang.space时就会转发到 http://www.baidu.com

本地一个端口转发到另一个端口或另一个域名

1
2
3
4
5
6
7
8
9
10
11
12
server{
listen 80;
server_name 127.0.0.1; # 公网ip
index index.php index.html index.htm;

location / {
proxy_pass http://127.0.0.1:8080; # 或 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;
}
}

这样访问 http://127.0.0.1 时就会转发到本地的 8080 端口或 http://www.baidu.com

加/与不加/

在配置proxy_pass代理转发时,如果后面的url加/,表示绝对根路径、如果没有/,表示相对路径

例如

1.加/

1
2
3
4
server_name liuxiangyang.space
location /data/ {
proxy_pass http://127.0.0.1/;
}

访问 http://liuxiangyang.space/data/index.html 会转发到 http://127.0.0.1/index.html

2.不加/

1
2
3
4
server_name liuxiangyang.space
location /data/ {
proxy_pass http://127.0.0.1;
}

访问 http://liuxiangyang.space/data/index.html 会转发到 http://127.0.0.1/data/index.html