坑 Nginx 在location 中使用 root 指令和alias 指令 遇到的問題

背景: Nginx 中想在 一個(gè)location 中通過root 指令單獨(dú)定義一個(gè)linux 系統(tǒng)下的目錄當(dāng)作此location 讀取資源的目錄。

以下測試場景發(fā)起請求的url : http://192.168.8.198:19999

遇到的坑: 當(dāng)我在location 中用精確匹配(=) 進(jìn)行匹配在同一個(gè)location 中使用root 指令指定資源目錄時(shí), 此時(shí)nginx會讀取 它的默認(rèn)資源目錄(nginx/html),無法達(dá)請求到我所指定目錄下資源。

#代碼示例
server{
        listen 19999  ;
       server_name www.test.com;
         #root /html/www/;
        error_log /nginx/logs/test.log;
        access_log /nginx/logs/test.log;

        location = / {
            root /html/www/;
            index index.html;
        }
}

經(jīng)過測試驗(yàn)證,總結(jié)以下規(guī)律:

經(jīng)過測試發(fā)現(xiàn) alias 指令和root指令此場景使用效果相同

  1. 在location 中使用精確匹配時(shí),通過root 指令 在http、或server 中指定資源目錄(/html/www/)就可以被讀取到。

    #代碼示例
    server{
            listen 19999  ;
           server_name www.test.com;
              root /html/www/;
            error_log /nginx/logs/test.log;
            access_log /nginx/logs/test.log;
    
            location = / {
                index index.html;
            }
    }
    
  2. 在location 中 使用^~、 ~ 、 ~*、/等匹配方式,,通過root 指令指定資源目錄(/html/www/) 也可以被正常讀取到。

    #代碼示例
    server{
            listen 19999  ;
            server_name www.test.com;
            error_log /nginx/logs/test.log;
            access_log /nginx/logs/test.log;
    
            location ~ / {
                     root /html/www/;
                index index.html;
            }
    }
    

驗(yàn)證上一個(gè)場景的過程中,總結(jié) root指令 和 alias 指令 使用的一些區(qū)別

若用alias的話,則訪問/img/目錄里面的文件時(shí),ningx會自動去/var/www/image/目錄找文件,比如:

發(fā)起請求 http://192.168.8.198:19999/local 則是對應(yīng)到服務(wù)器下的/html/www/index.html, 說明 在使用alias 指令時(shí),location 處的 匹配只做請求的匹配驗(yàn)證,請求帶的uri 不會更改alias 指定的資源目錄。

 location   /local {
            alias /html/www/;
            index index.html;
        }

若用root的話,則訪問/img/目錄下的文件時(shí),nginx會去/var/www/image/img/目錄下找文件 ,比如:

發(fā)起請求http://192.168.8.198:19999/www則是對應(yīng)服務(wù)器下的/html/www/index.html,說明 請求帶的uri 中的路徑會自動拼接到root指定的資源目錄后邊。

 location   /www {
            root /html/;
            index index.html;
        }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容