Nginx中的location路徑映射問題
Nginx location路徑映射
nginx 配置 proxy_pass時可以實現(xiàn)URL路徑的部分替換
1.proxy_pass的目標(biāo)地址后,默認(rèn)不帶/,表示只代理域名,url和querystring部分不會變(把請求的path拼接到proxy_pass目標(biāo)域名之后作為代理的URL)
2.目標(biāo)地址后帶/,則表示把path中l(wèi)ocation匹配成功的部分剪切掉之后再拼接到proxy_pass目標(biāo)地址
例子:
server { location /xxx { proxy_pass http://server_url; } location /xxx { proxy_pass http://server_url/; } }
比如請求 域名/xxx/index.html
實際代理的目標(biāo)url分別是
- proxy_pass不帶/:http://server_url/xxx/index.html(直接拼接到路徑后)
- proxy_pass帶/:http://server_url/index.html (xxx被去掉)
Nginx的location匹配規(guī)則
Nginx的location語法
location [=|~|~*|^~] /uri/ { … }
- = 嚴(yán)格匹配。如果請求匹配這個location,那么將停止搜索并立即處理此請求
- ~ 區(qū)分大小寫匹配(可用正則表達(dá)式)
- ~* 不區(qū)分大小寫匹配(可用正則表達(dá)式)
- !~ 區(qū)分大小寫不匹配
- !~* 不區(qū)分大小寫不匹配
- ^~ 如果把這個前綴用于一個常規(guī)字符串,那么告訴nginx 如果路徑匹配那么不測試正則表達(dá)式
示例1:
location / { }
匹配任意請求
示例2:
location ~* .(gif|jpg|jpeg)$ { rewrite .(gif|jpg|jpeg)$ /logo.png; }
不區(qū)分大小寫匹配任何以gif、jpg、jpeg結(jié)尾的請求,并將該請求重定向到 /logo.png請求
location ~ ^.+\.txt$ { root /usr/local/nginx/html/; }
區(qū)分大小寫匹配以.txt結(jié)尾的請求,并設(shè)置此location的路徑是/usr/local/nginx/html/。
也就是以.txt結(jié)尾的請求將訪問/usr/local/nginx/html/ 路徑下的txt文件
alias與root的區(qū)別
- root 實際訪問文件路徑會拼接URL中的路徑
- alias 實際訪問文件路徑不會拼接URL中的路徑
示例如下:
location ^~ /sta/ { alias /usr/local/nginx/html/static/; }
- 請求:http://test.com/sta/sta1.html
- 實際訪問:/usr/local/nginx/html/static/sta1.html 文件
location ^~ /tea/ { root /usr/local/nginx/html/; }
- 請求:http://test.com/tea/tea1.html
- 實際訪問:/usr/local/nginx/html/tea/tea1.html 文件
last 和 break關(guān)鍵字的區(qū)別
(1)last 和 break 當(dāng)出現(xiàn)在location 之外時,兩者的作用是一致的沒有任何差異
(2)last 和 break 當(dāng)出現(xiàn)在location 內(nèi)部時:
- last 使用了last 指令,rewrite 后會跳出location 作用域,重新開始再走一次剛才的行為
- break 使用了break 指令,rewrite后不會跳出location 作用域,它的生命也在這個location中終結(jié)
permanent 和 redirect關(guān)鍵字的區(qū)別
- rewrite … permanent 永久性重定向,請求日志中的狀態(tài)碼為301
- rewrite … redirect 臨時重定向,請求日志中的狀態(tài)碼為302
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Nginx中虛擬主機(jī)與指定訪問路徑的設(shè)置方法講解
這篇文章主要介紹了Nginx中虛擬主機(jī)與指定訪問路徑的設(shè)置方法講解,也是在同一個Nginx程序中部署多個站點的基本方法,需要的朋友可以參考下2016-03-03詳解nginx rewrite和根據(jù)url參數(shù)location
本篇文章主要是介紹了nginx rewrite和根據(jù)url參數(shù)location,有興趣的同學(xué)可以了解以下。2016-11-11