zoukankan      html  css  js  c++  java
  • Nginx if 条件判断

    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

        http://www.nginx.cn/784.html

        https://www.lvtao.net/config/644.html

  • 相关阅读:
    Redis配置参数详解
    amoeba实现读写分离
    P1525 关押罪犯 并查集
    模板汇总——treap
    差分约束
    HDU
    CodeForces 522C Chicken or Fish?
    CodeForces 812E Sagheer and Apple Tree 树上nim
    CodeForces 855E Salazar Slytherin's Locket
    CodeForces 283C World Eater Brothers
  • 原文地址:https://www.cnblogs.com/saneri/p/6257188.html
Copyright © 2011-2022 走看看