有時我們會使用一些java或node應用,但又不想讓他們直接監聽80端口,這時就需要用到端口轉發
本文中,我們介紹Nginx如何做端口轉發,還有各種轉發規則
將域名轉發到本地端口
首先介紹最常用的,將域名轉發到本地另一個端口上
server{ listen 80; server_name tomcat.shaochenfeng.com; 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://tomcat.shaochenfeng.com 時就會轉發到本地的 8080 端口
將域名轉發到另一個域名
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; } }
本地一個端口轉發到另一個端口或另一個域名
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; } }
加 / 與不加 /
在配置proxy_pass代理轉發時,如果后面的url加/,表示絕對根路徑;如果沒有/,表示相對路徑
例如
加 /
server_name shaochenfeng.com location /data/ { proxy_pass http://127.0.0.1/; }
訪問 http://shaochenfeng.com/data/index.html 會轉發到 http://127.0.0.1/index.html
不加 /
server_name shaochenfeng.com location /data/ { proxy_pass http://127.0.0.1; }
訪問 http://shaochenfeng.com/data/index.html 會轉發到 http://127.0.0.1/data/index.html