location正則寫法
一個示例:
location = / {
# 精確匹配 / ,主機名後面不能帶任何字串
[ configuration A ]
}
location / {
# 因為所有的地址都以 / 開頭,所以這條規則將匹配到所有請求
# 但是正則和最長字串會優先匹配
[ configuration B ]
}
location /documents/ {
# 匹配任何以 /documents/ 開頭的地址,匹配符合以後,還要繼續往下搜尋
# 只有後面的正規表示式沒有匹配到時,這一條才會採用這一條
[ configuration C ]
}
location ~ /documents/Abc {
# 匹配任何以 /documents/ 開頭的地址,匹配符合以後,還要繼續往下搜尋
# 只有後面的正規表示式沒有匹配到時,這一條才會採用這一條
[ configuration CC ]
}
location ^~ /images/ {
# 匹配任何以 /images/ 開頭的地址,匹配符合以後,停止往下搜尋正則,採用這一條。
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# 匹配所有以 gif,jpg或jpeg 結尾的請求
# 然而,所有請求 /images/ 下的圖片會被 config D 處理,因為 ^~ 到達不了這一條正則
[ configuration E ]
}
location /images/ {
# 字元匹配到 /images/,繼續往下,會發現 ^~ 存在
[ configuration F ]
}
location /images/abc {
# 最長字元匹配到 /images/abc,繼續往下,會發現 ^~ 存在
# F與G的放置順序是沒有關係的
[ configuration G ]
}
location ~ /images/abc/ {
# 只有去掉 config D 才有效:先最長匹配 config G 開頭的地址,繼續往下搜尋,匹配到這一條正則,採用
[ configuration H ]
}
location ~* /js/.*/\.js
已=
http://tengine.taobao.org/book/chapter_02.html
http://nginx.org/en/docs/http/ngx_http_rewrite_module.html
Rewrite規則
rewrite功能就是,使用nginx提供的全域性變數或自己設定的變數,結合正規表示式和標誌位實現url重寫以及重定向。rewrite只能放在server{},location{},if{}中,並且只能對域名後邊的除去傳遞的引數外的字串起作用,例如 http://seanlook.com/a/we/index.php?id=1&u=str
全域性變數
下面是可以用作if判斷的全域性變數
$args
對形如/images/ef/uh7b3/test.png
對形如/images/bla_500x400.jpg
的檔案請求,重寫到/resizer/bla.jpg?width=500&height=400
地址,並會繼續嘗試匹配location。
例3:
見 ssl部分頁面加密 。
參考
http://www.nginx.cn/216.html
http://www.ttlsa.com/nginx/nginx-rewriting-rules-guide/
《老僧系列nginx之rewrite規則快速上手.pdf》
http://fantefei.blog.51cto.com/2229719/919431
原文連結地址:http://seanlook.com/2015/05/17/nginx-location-rewrite/
写评论