一 Nginx的location語法
location [=||*|^~] /uri/ { … }
- = 嚴格匹配。如果請求匹配這個location,那麼將停止搜索並立即處理此請求
- ~ 區分大小寫匹配(可用正則表達式)
- ~* 不區分大小寫匹配(可用正則表達式)
- !~ 區分大小寫不匹配
- !~* 不區分大小寫不匹配
- ^~ 如果把這個前綴用於一個常規字符串,那麼告訴nginx 如果路徑匹配那麼不測試正則表達式
示例1:
匹配任意請求
location / { }
示例2:
不區分大小寫匹配任何以gif、jpg、jpeg結尾的請求,並將該請求重定向到 /logo.png請求
location ~* .(gif|jpg|jpeg)$ {
rewrite .(gif|jpg|jpeg)$ /logo.png;
}
示例3:
區分大小寫匹配以.txt結尾的請求,並設置此location的路徑是/usr/local/nginx/html/。也就是以.txt結尾的請求將訪問/usr/local/nginx/html/ 路徑下的txt文件
location ~ ^.+\.txt$ {
root /usr/local/nginx/html/;
}
二 alias與root的區別
- root 實際訪問文件路徑會拼接URL中的路徑
- alias (別名) 實際訪問文件路徑不會拼接URL中的路徑
alias示例:
請求:http://test.com/sta/sta1.html
實際訪問:/usr/local/nginx/html/static/sta1.html 文件
location ^~ /sta/ {
alias /usr/local/nginx/html/static/;
}
root示例:
請求:http://test.com/tea/tea1.html
實際訪問:/usr/local/nginx/html/tea/tea1.html 文件
location ^~ /tea/ {
root /usr/local/nginx/html/;
}
三 last 和 break關鍵字的區別
-
last 和 break 當出現在location 之外時,兩者的作用是一致的沒有任何差異
-
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關鍵字:
這裏將所有符合條件的URL(PS:不區分大小寫)都重定向到/testpage.txt請求,也就是 /usr/local/nginx/html/testpage.txt 文件
location ~ ^.+\.txt$ {
root /usr/local/nginx/html/;
}
location ~* ^/test/(\d+)/[\w-\.]+$ {
rewrite ^/test/(\d+)/[\w-\.]+$ /testpage.txt last;
}
使用alias關鍵字:
這裏將所有符合條件的URL(PS:不區分大小寫)都重定向到/usr/local/nginx/html/static/sta1.html 文件
location ~* ^/test/(\d+)/[\w-\.]+$ {
alias /usr/local/nginx/html/static/sta1.html;
}