在上一篇文章:《Nginx if語句加正則表達式實現字符串截斷》中, 我們介紹過了使用if來進行截斷字符串的用法, 這次我們來了解下if的邏輯用法:
什么是邏輯用法呢, 就程序中的and、or關系, 就叫做邏輯了.
NGINX支持if的 and 與 or 或者 && 與 || 嗎?
答案是No.
當你嘗試這樣配置, 重載nginx時, nginx會報出錯誤
代碼如下:
location = /test/ {
default_type text/html;
set $b 0;
if ( $remote_addr != '' && $http_x_forwarded_for != '' ){
set $b '1';
}
echo $b;
}
[root@test-vm ~]# /usr/local/nginx/sbin/nginx -t
nginx: [emerg] invalid condition "$remote_addr" in /usr/local/nginx/conf/nginx.conf:60
configuration file /usr/local/nginx/conf/nginx.conf test failed
那么我們應該怎樣來實現and 和or的邏輯關系呢?
代碼如下:
location = /test_and/ {
default_type text/html;
set $a 0;
set $b 0;
if ( $remote_addr != '' ){
set $a 1;
}
if ( $http_x_forwarded_for != '' ){
set $a 1$a;
}
if ( $a = 11 ){
set $b 1;
}
echo $b;
}
location = /test_or/ {
default_type text/html;
set $a 0;
set $b 0;
if ( $remote_addr != '' ){
set $a 1;
}
if ( $http_x_forwarded_for != '' ){
set $a 1;
}
if ( $a = 1 ){
set $b 1;
}
新聞熱點
疑難解答