https://www.cnblogs.com/saneri/p/6257188.html
Nginx if 條件判斷:
1.公司網站上線有這樣的需求:
由於公司網站域名從http到https的轉移,在測試階段需要公司內部進行測試,公司內部局域網訪問時強制訪問加密的https服務,外部用戶訪問正常的http服務.
第一種方法:
if ( $http_x_forwarded_for ~ ^106\.38\.53\.130|210\.12\.103\.18) {
return 301 https://www.xxx.cn$request_uri;
}
#有的說nginx不支持這種if寫法,但我在nginx配置后是成功了,可能是版本高了以后,nginx也支持呢。我的nginx是1.8.0版本.
第二種方法:
#用變量的方式來間接實現
set $flag 0;
if ( $http_x_forwarded_for ~ ^106\.38\.53\.130|210\.12\.103\.18) {
set $flag "${flag}1";
}
if ($flag = "01") {
return 301 https://www.xxx.cn$request_uri;
}
$remote_addr 為獲取客戶端訪問地址,如果網站使用了前端代理或負載均衡的話使用$http_x_forwarded_for
####################################################################################################
2.當訪問某個php應用時,我只想讓ip地址為106.38.53.130訪問,別的ip都跳轉至另一個頁面。如下:
#訪問/cms/index.php,且ip地址不是106.38.53.130的跳轉到https://www.xxoo.cn
set $ssl_80 '';
if ( $request_uri ~* /cms/index.php ) { //客戶端請求的完整請求路徑
set $ssl_80 A;
}
if ( $http_x_forwarded_for !~* ^106\.38\.53\.130.* ) { //前端有負載均衡的客戶端ip地址
set $ssl_80 "${ssl_80}B";
}
#if ( $remote_addr !~* ^10\.105\.99\.158.* ) { //客戶端ip地址
# set $ssl_80 "${ssl_80}C";
#}
if ( $ssl_80 = AB ) {
#return 403;
rewrite ^(.*)$ https://www.xxoo.cn permanent;
}
$request_uri是客戶端請求的完整路徑
$http_user_agent 是用戶端發出請求的瀏覽器參數
$args 請求中的參數值
3.Nginx區分PC或手機訪問不同網站
location / {
proxy_pass http://10.10.100.60:8183;
if ( $http_user_agent ~* "(mobile|nokia|iPhone|ipad|android|samsung|htc|blackberry)" )
{
rewrite ^/$ http://www.baidu.com;
}
index index.html index.htm;
}
參考文檔:
http://www.360doc.com/content/15/0119/14/15398874_442036739.shtml
http://www.cnblogs.com/raichen/p/5121262.html
https://my.oschina.net/boonya/blog/287265
https://www.lvtao.net/config/644.html


