關於Nginx請求URL自動添加斜槓/的端口問題

關於Nginx請求URL自動添加斜槓/的端口問題


概述

最近在使用Nginx做了兩層,第一層爲用戶訪問的Nginx反向代理,監聽端口爲80,第二層爲處理本地靜態文件、並將json數據請求代理到apche,監聽端口爲8080。在測試的過程中,發現一個小問題,就是當請求的URL沒有斜槓時,會自動默認301跳,轉添加反斜槓/,通過Location跳轉,跳轉時帶上了後端nginx的端口,比如:

當我請求一下地址爲:http://www.easysb.cn/product時,返回的請求結果爲Location跳轉,新的URL爲http://www.easysb.cn:8080/product/,導致瀏覽器無法正確訪問。

解決方案

通過查閱Nginx相關的文檔,找到三個和此相關的配置指令,分別爲:

Syntax:	absolute_redirect on | off;
Default:	absolute_redirect on;
Context:	http, server, location
This directive appeared in version 1.11.8.

If disabled, redirects issued by nginx will be relative.
Syntax:	server_name_in_redirect on | off;
Default:	server_name_in_redirect off;
Context:	http, server, location
Enables or disables the use of the primary server name, specified by the 
server_name directive, in absolute redirects issued by nginx. When the 
use of the primary server name is disabled, the name from the “Host” 
request header field is used. If this field is not present, the IP 
address of the server is used.
Syntax:	port_in_redirect on | off;
Default:	port_in_redirect on;
Context:	http, server, location
Enables or disables specifying the port in absolute redirects issued 
by nginx.

簡單來說,absolute_redirect是指控制跳轉的url是絕對路徑還是相對路徑,這個指令是在1.11.8版本纔出現。絕對路徑就是剛剛上面的http://www.easysb.cn/product,相對路徑就是/product。很顯然,只有在這個開關爲開的時候,纔會影響到後面兩個指令。我這部署的nginx爲1.10.1,所以在1.11.8之前應該都是開的。

server_name_in_redirect指令是隻跳轉的URL的域名是用配置文件nginx.conf中的配置的server_name,還是用請求中獲取。默認值爲off,即從請求中獲取。

port_in_redirect指令是隻跳轉的URL的端口是用配置文件nginx.conf中的配置的port,還是用請求中獲取。默認值爲on,即配置文件定義。

瞭解完三個指令之後,就很容易解決了,只需要將第二個nginx的port_in_redirect將其關閉,直接從請求中獲取,即:

 
# absolute_redirect on # 只有1.11.8 才支持,低版本不需要配置
server_name_in_redirect off;
port_in_redirect off;

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章