1. 程式人生 > >[記錄]Nginx配置實現&&和||的方法實例

[記錄]Nginx配置實現&&和||的方法實例

搜索 替換 log nginx urn || 規則 location 支持

Nginx配置文件中if的&&和||的實現(nginx不支持&&和||的寫法)


1.與(&&)的寫法:


set $condiction ‘‘;
if ($http_user_agent ~ "Chrome"){
set $condiction a;
}
if ($args ~ "r=hao123"){
set $condiction "${condiction}b";
}
if ($condiction = ab){
rewrite ^/(.*)$ https://www.hao123.com/?tn=94408350_hao_pg;
}
說明:當瀏覽器是Chrome並且url的參數是r=hao123的時候做重定向。

  rewrite有四個flag,不帶flag時默認是redirect(302),如下:

  1)last(重寫後的規則,會繼續用重寫後的值去匹配下面的location。)

  2)break(重寫後的規則,不會去匹配下面的location。使用新的規則,直接發起一次http請求了。)

  3)permanent(301永久重定向,搜索引擎在抓取新內容的同時也將舊的網址替換為重定向之後的網址)

  4)redirect(302臨時重定向,搜索引擎會抓取新的內容而保留舊的網址)(網站換量的場景下使用)

2.或(||)的寫法:


set $condiction 0;
if ($http_x_forwarded_for ~ " ?xxx\.xxx\.xxx\.xx1$"){
set $condiction 1;
}
if ($http_x_forwarded_for ~ " ?xxx\.xxx\.xxx\.xx2$"){
set $condiction 1;
}
if ($condiction){
rewrite ^/(.*)$ https://www.hao123.com/?tn=94408350_hao_pg;
}
說明:當ip是xxx.xxx.xxx.xx1或xxx.xxx.xxx.xx2的時候做重定向。

3.結合上面兩段代碼,實現禁止IP訪問,禁止Chrome瀏覽器並且url參數是r=hao123的訪問。
set $condiction1 true;
set $condiction2 ‘‘;
if ($http_user_agent ~ "Chrome") {
set $condiction2 a;
}
if ($args ~ "r=hao123") {
set $condiction2 "${condiction2}b";
}
if ($condiction2 = ab) {
set $condiction1 false;
}

if ($http_x_forwarded_for ~ " ?xxx\.xxx\.xxx\.xx1$") {
set $condiction1 false;
}
if ($http_x_forwarded_for ~ " ?xxx\.xxx\.xxx\.xx2$") {
set $condiction1 false;
}

if ($condiction1 = false) {
return 403;
}

[記錄]Nginx配置實現&&和||的方法實例