有时我们会使用一些
java
或node
应用,但又不想让他们直接监听80
端口,这时就需要用到端口转发。
本文中,我们介绍Nginx
如何做端口转发,还有各种转发规则。
可以配置多条代理规则 ,一条代理使用一个server {}
块。
注意配置项的每一行都要以分号结尾,否则会报错。
1,将域名转发到本地指定端口
server {
# 监听端口
listen 80;
# 要匹配转发的域名(多个域名之间用空格分隔)
server_name example.com www.example test.com;
# 首页文件顺序
index index.php index.html index.htm;
# 访问80 端口,跳转到8080端口
location / {
proxy_pass http://127.0.0.1:8080;
# 修改转发请求头,让8080端口的应用可以收到真实的请求
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;
}
}
这样访问匹配的域名时就会转发到本地的 8080 端口
2,将域名转发到另一个域名
server{
listen 80;
server_name baidu.example.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;
}
}
这样访问匹配的域名时就会转发到百度。
3, 本地一个端口转发到另一个端口或另一个域名
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 端口或百度
加 / 与不加 /
在配置proxy_pass代理转发时,如果后面的url加/,表示绝对根路径;如果没有/,表示相对路径
例如
1,加 /
server_name example.com
location /data/ {
proxy_pass http://127.0.0.1/;
}
访问 http://example.com/data/index.html
会转发到 http://127.0.0.1/index.html
2,不加 /
server_name example.com
location /data/ {
proxy_pass http://127.0.0.1;
}
访问 http://example.com/data/index.html
会转发到 http://127.0.0.1/data/index.html
本篇文章转自:https://zhuanlan.zhihu.com/p/108740468,内容有少许修改。