Nginx_location的匹配規則的使用方法與實例
阿新 • • 發佈:2019-01-11
訪問 iis perm 使用方法 匹配 行為 ref href 綜合實例 一 Nginx的location語法
location [=|——|——*|^——] /uri/ { … }
= 嚴格匹配。如果請求匹配這個location,那麽將停止搜索並立即處理此請求
—— 區分大小寫匹配(可用正則表達式)
——* 不區分大小寫匹配(可用正則表達式)
!—— 區分大小寫不匹配
!——* 不區分大小寫不匹配
^—— 如果把這個前綴用於一個常規字符串,那麽告訴nginx 如果路徑匹配那麽不測試正則表達式
示例1:
location / { }
匹配任意請求
示例2:
location ——* .(gif|jpg|jpeg)$ {
rewrite .(gif|jpg|jpeg)$ /logo.png;
}
不區分大小寫匹配任何以gif、jpg、jpeg結尾的請求,並將該請求重定向到 /logo.png請求
示例3:
location —— ^.+\.txt$ {
root /usr/local/nginx/html/;
}
區分大小寫匹配以.txt結尾的請求,並設置此location的路徑是/usr/local/nginx/html/。也就是以.txt結尾的請求將訪問/usr/local/nginx/html/ 路徑下的txt文件
二 alias與root的區別
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關鍵字的區別
(1)last 和 break 當出現在location 之外時,兩者的作用是一致的沒有任何差異
(2)last 和 break 當出現在location 內部時:
last 使用了last 指令,rewrite 後會跳出location 作用域,重新開始再走一次剛才的行為
break 使用了break 指令,rewrite後不會跳出location 作用域,它的生命也在這個location中終結
四 permanent 和 redirect關鍵字的區別
rewrite … permanent 永久性重定向,請求日誌中的狀態碼為301
rewrite … redirect 臨時重定向,請求日誌中的狀態碼為302
五 綜合實例
將符合某個正則表達式的URL重定向到一個固定頁面
比如:我們需要將符合“/test/(\d+)/[\w-\.]+” 這個正則表達式的URL重定向到一個固定的頁面。符合這個正則表達式的頁面可能是:http://test.com/test/12345/abc122.html、http://test.com/test/456/11111cccc.js等FTP
從上面的介紹可以看出,這裏可以使用rewrite重定向或者alias關鍵字來達到我們的目的。因此,這裏可以這樣做:
(1)使用rewrite關鍵字:
location —— ^.+\.txt$ {
root /usr/local/nginx/html/;
}
location ——* ^/test/(\d+)/[\w-\.]+$ {
rewrite ^/test/(\d+)/[\w-\.]+$ /testpage.txt last;
}
這裏將所有符合條件的URL(PS:不區分大小寫)都重定向到/testpage.txt請求,也就是 /usr/local/nginx/html/testpage.txt 文件
(2)使用alias關鍵字:
location ——* ^/test/(\d+)/[\w-\.]+$ {
alias /usr/local/nginx/html/static/sta1.html;
}
這裏將所有符合條件的URL(PS:不區分大小寫)都重定向到/usr/local/nginx/html/static/sta1.html 文件
Nginx_location的匹配規則的使用方法與實例