文章詳情頁
nginx多location配置實例代碼
瀏覽:107日期:2023-06-15 15:23:26
目錄
- 前言
- nginx常用正則表達式
- 實測
- 備注
- 總結
前言
nginx server下配置多個location根據路徑匹的不同做不同的處理。
nginx常用正則表達式
語法規則: location [=|~|~*|^~] /uri/ { … }
- = 開頭表示:精確匹配。
- ^~ 開頭表示:區分大小寫以什么開頭。
- ~ 開頭表示:區分大小寫的正則匹配。
- ~* 開頭表示:不區分大小寫的正則匹配。
- !~ 和!~*分別表示:區分大小寫 不匹配 及不區分大小寫 不匹配的正則匹配。
- / 表示:通用匹配,任何請求都會匹配到。
多個location配置的情況下匹配順序為(未驗證):
首先匹配 =,其次匹配^~, 其次是按文件中順序的正則匹配,最后是交給 / 通用匹配。當有匹配成功時候,停止匹配,按當前匹配規則處理請求。
實測
server { listen 80; listen [::]:80; server_name location.test.com; access_log /var/log/nginx/location.host.access.log main; #*********************注意多個location通常按精確的放前面,模糊大范圍的放后面,nginx先找= ****************************** location = /login.html {#精確匹配 /login root /usr/share/nginx/html/test-equal;#請求/login.html相當于尋找資源/usr/share/nginx/html/test-equal/login.html } location ^~ /prefix/ {#區分大小寫且以/prefix/開頭 root /usr/share/nginx/html/test-prefix;#root代表根目錄,請求/prefix/prefix.html相當于尋找資源/usr/share/nginx/html/test-prefix/prefix/prefix.html } location ~ \.(png|jpg)$ {#不區分大小寫且以.png或.jpg結尾 root /usr/share/nginx/html/test-suffix;#請求/suffix/a.png相當于尋找資源/usr/share/nginx/html/test-suffix/suffix/a.png } location ^~ /jd/ {# 區分大小寫且以/jd/開頭 proxy_pass https://www.jd.com/;#proxy_pass 此處的url以/結尾,則nginx會取掉location部分再轉發,例如,請求/jd/電器?name=1 則會轉發到https://www.jd.com/電器?name=1 } location ^~ /s {# /會匹配到所有的 proxy_pass https://www.baidu.com;#proxy_pass 此處的url沒有以/結尾,則匹配到的地址全部拼接到代理后的地址,例如,請求/s?name=1 則會轉發到https://www.baidu.com/s?name=1 } location / {# 會返回index.html root /usr/share/nginx/html; index index.html; } }
備注
location下的root和alias區別:
例子:
客戶端請求:http://localhost:8080/user/info/a.txt
nginx如果用root配置:nginx會去尋找資源:/home/html/user/info/a.txt
location ^~ /user {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E--> root /home/html;#此處可以不以/結尾 }
nginx如果用alias配置:nginx會去尋找資源:/home/html/info/a.txt
location ^~ /user {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E--> alias /home/html/;#此處以/結尾 }
總結
到此這篇關于nginx多location配置的文章就介紹到這了,更多相關nginx多location配置內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!
標簽:
Nginx
上一條:一文帶你搞懂什么是Nginx服務器下一條:淺談一下Nginx性能優化
排行榜
