nginx多l(xiāng)ocation配置實例代碼
前言
nginx server下配置多個location根據(jù)路徑匹的不同做不同的處理。
nginx常用正則表達式
語法規(guī)則: location [=|~|~*|^~] /uri/ { … }
- = 開頭表示:精確匹配。
- ^~ 開頭表示:區(qū)分大小寫以什么開頭。
- ~ 開頭表示:區(qū)分大小寫的正則匹配。
- ~* 開頭表示:不區(qū)分大小寫的正則匹配。
- !~ 和!~*分別表示:區(qū)分大小寫 不匹配 及不區(qū)分大小寫 不匹配的正則匹配。
- / 表示:通用匹配,任何請求都會匹配到。
多個location配置的情況下匹配順序為(未驗證):
首先匹配 =,其次匹配^~, 其次是按文件中順序的正則匹配,最后是交給 / 通用匹配。當有匹配成功時候,停止匹配,按當前匹配規(guī)則處理請求。
實測
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/ {#區(qū)分大小寫且以/prefix/開頭
root /usr/share/nginx/html/test-prefix;#root代表根目錄,請求/prefix/prefix.html相當于尋找資源/usr/share/nginx/html/test-prefix/prefix/prefix.html
}
location ~ \.(png|jpg)$ {#不區(qū)分大小寫且以.png或.jpg結(jié)尾
root /usr/share/nginx/html/test-suffix;#請求/suffix/a.png相當于尋找資源/usr/share/nginx/html/test-suffix/suffix/a.png
}
location ^~ /jd/ {# 區(qū)分大小寫且以/jd/開頭
proxy_pass https://www.jd.com/;#proxy_pass 此處的url以/結(jié)尾,則nginx會取掉location部分再轉(zhuǎn)發(fā),例如,請求/jd/電器?name=1 則會轉(zhuǎn)發(fā)到https://www.jd.com/電器?name=1
}
location ^~ /s {# /會匹配到所有的
proxy_pass https://www.baidu.com;#proxy_pass 此處的url沒有以/結(jié)尾,則匹配到的地址全部拼接到代理后的地址,例如,請求/s?name=1 則會轉(zhuǎn)發(fā)到https://www.baidu.com/s?name=1
}
location / {# 會返回index.html
root /usr/share/nginx/html;
index index.html;
}
}
備注
location下的root和alias區(qū)別:
例子:
客戶端請求: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;#此處可以不以/結(jié)尾
}
nginx如果用alias配置:nginx會去尋找資源:/home/html/info/a.txt
location ^~ /user {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->
alias /home/html/;#此處以/結(jié)尾
}總結(jié)
到此這篇關(guān)于nginx多l(xiāng)ocation配置的文章就介紹到這了,更多相關(guān)nginx多l(xiāng)ocation配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Apache Nginx 禁止目錄執(zhí)行PHP腳本文件的方法
這篇文章主要介紹了Apache Nginx 禁止目錄執(zhí)行PHP腳本文件的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
nginx中使用nginx-http-concat模塊合并靜態(tài)資源文件
這篇文章主要介紹了nginx中使用nginx-http-concat模塊合并靜態(tài)資源文件,用以加速網(wǎng)站的CSS、JS等靜態(tài)資源載入速度,需要的朋友可以參考下2014-06-06
封80端口應對策略 Nginx反向代理For WIN2003超級傻瓜式配置
封80應對策略,Nginx反向代理ForWIN2003超級傻瓜式配置!2010-03-03
Nginx+ModSecurity安全模塊部署的實現(xiàn)
本文主要介紹了Nginx+ModSecurity安全模塊部署的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08

