location之alias淺析


在一個server中,如果需要根據前綴訪問不同文件夾下的文件,則可以使用alias來設置。
如下代碼:

    server {
        listen 9085;
        server_name 127.0.0.1;
        absolute_redirect off;
        #server_name_in_redirect off;
        
        
        #root D:/dotnet/netframework/siteserver_install/;
        index index.html;
        
        location = / {
            proxy_pass http://127.0.0.1:8084/index.html;
        }
        
        location / {
            proxy_pass http://127.0.0.1:8085/;    
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }        
        
        location /eduinfo/ {
            alias D:/dotnet/netframework/Test/;            
            expires 24h;
        }
        
        location /mytest {
            alias D:/dotnet/mytestfolder;
            expires 24h;            
        }    
    }
    
在這個server配置中,使用index指定了目錄下的默認訪問文件,如下圖:

 即訪問的URL若沒有指向具體文件,則會訪問URL目錄下的index.html文件。 

 

接下來讓我們看看配置時,目錄后面帶/斜杠和不帶/斜杠的區別。
1、location目錄結尾帶斜杠時,如: location /eduinfo/ 這種配置時:
訪問 localhost:9085/eduinfo時的結果:

 

訪問localhost:9085/eduinfo/時的結果:

 從結果來看,證明location配置目錄時,結尾帶斜杠的需要精確匹配到/斜杠才行。

 

2、location目錄結尾沒有帶/斜杠,如:localhost:9085/mytest這種配置時:
訪問 localhost:9085/mytest時的結果:

   

訪問localhost:9085/mytest/時的結果:

從結果來看,使用location /mytest 這種結尾不帶斜杠的配置時,nginx會自動301跳轉到帶上一個/斜杠的URL,並訪問其目錄下的index..html文件。

 

 


免責聲明!

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



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