nginx url自動加斜杠的問題


nginx url自動加斜杠問題及301重定向

時間:2016-02-04 15:14:28來源:網絡
導讀:nginx url自動加斜杠問題及301重定向,URL指向一個目錄並且在最后沒有包含斜杠,會301重定向跳轉,添加server_name或修改訪問重定向。
 
nginx url自動加斜杠問題及301重定向

內部服務器使用nginx,做網站測試之用。不同域名使用端口號區分,如www用默認的80端口,其它域名用81,82...

有時直接在地址欄敲網址,會發現跳轉到localhost.localdomain的情況。

比如858端口下有個hx目錄,這樣正常訪問:http://192.168.1.158:858/hx/
但如果少打了一個/,如:http://192.168.1.158:858/hx
就會自動跳轉到:http://localhost.localdomain:858/hx/

經分析是nginx自動加斜杠的問題:
在某些情況下(具體可參考 wiki.nginx.org),Nginx 內部重定向規則會被啟動。
例如,當URL 指向一個目錄並且在最后沒有包含“/”時,Nginx 內部會自動的做一個 301 重定向,這時會有兩種情況:
 

1、server_name_in_redirect on(默認),URL 重定向為: server_name 中的第一個域名 + 目錄名 + /;
2、server_name_in_redirect off,URL 重定向為: 原 URL 中的域名 + 目錄名 + /。
If server_name_in_redirect is on, then Nginx will use the first value of the server_name directive for redirects. If server_name_in_redirect is off, then nginx will use the requested Host header.

原配置,沒有加server_name:
 

server {
    listen  858;
}

修改后:
 

server {
    listen  858;
    server_name 192.168.1.158;
}
或:
server {
    listen  858;
    server_name_in_redirect off;
}

此問題解決。訪問http://192.168.1.158:858/hx可以正常跳轉到http://192.168.1.158:858/hx/了。

分析:
服務器的hostname是localhost.localdomain,當沒有設置server_name時,server_name就變成hostname了。

默認又是server_name_in_redirect on,因此原配置訪問hx目錄時,會重定向到localhost.localdomain/hx/了。

第一種修改方法,加了server_name,那就跳轉到server_name + 目錄名 + /,對了。

第二種修改訪問,重定向為:訪問的URL+目錄名+/,也對了。

泛解析配置:
 

server{
    listen 80;
    server_name _;
}
 

如果有個phpcheck目錄,有人不小心鏈了http://www.plchome.org/phpcheck這樣一個鏈接,就會重定向到http://_/phpcheck/。
所以這種在沒法指定server_name的情況下,要加上server_name_in_redirect off。
 

server{
    listen 80;
    server_name _;
    server_name_in_redirect off;
}
 

這時,訪問www.plchome.org/phpcheck,就會自動並且正確的跳轉到www.plchome.org/phpcheck/了。

晚上升級一台服務器的nginx版本時,在changes里看到:
 

Changes with nginx 0.8.48   03 Aug 2010

    *) Change: now the "server_name" directive default value is an empty 
       name "".
       Thanks to Gena Makhomed.

    *) Change: now the "server_name_in_redirect" directive default value is 
       "off".

從nginx 0.8.48起server_name_in_redirect已經默認為off了,不再需要指定了。

  相關文章


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM