Nginx的location匹配規則

原文鏈接:https://www.cnblogs.com/duhuo/p/8323812.html

一 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等

從上面的介紹可以看出,這裏可以使用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 文件

參考:

http://www.php100.com/html/program/nginx/2013/0905/5535.html
http://unixman.blog.51cto.com/10163040/1711943
https://my.oschina.net/aiguozhe/blog/115510
https://zhuanlan.zhihu.com/p/24524057
https://segmentfault.com/a/1190000002797606

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章