微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Nginx代理传递和URL重写

如果我在url中有GET参数(查询字符串),如何触发此规则,
否则我会匹配别名.

location ~^/static/photos/.* {
    rewrite ^/static/photos/(.*)$ /DynamicPhotoQualitySwitch/photos/$1  break;
    expires     7d;
    proxy_pass http://foofoofoo.com;
    include /etc/Nginx/proxy.conf;
     }

解决方法:

我知道的第一种方法是对$args参数使用正则表达式,如下所示:

    if ($args ~ "^(\w+)=") { 

或者第二种方式是使用方便的$is_args,如下所示:

    if ($is_args != "") {  

请记住,在两种样式中,您需要在if和左括号之间放置一个空格; “if(”not“if(”以及右括号和左括号之后的空格;“){”而不是“){”.

使用上面第一种风格的完整示例,Nginx.conf:

location ~^/static/photos/.* { 
    include /etc/Nginx/proxy.conf; 
    if ($args ~ "^(\w+)=") { 
            rewrite ^/static/photos/(.*)$ /DynamicPhotoQualitySwitch/photos/$1  break;
            expires     7d;
            proxy_pass http://foofoofoo.com; 
    }
}

使用上面第二种风格的完整示例,Nginx.conf:

location ~^/static/photos/.* { 
    include /etc/Nginx/proxy.conf; 
    if ($is_args != "") {  
            rewrite ^/static/photos/(.*)$ /DynamicPhotoQualitySwitch/photos/$1  break;
            expires     7d;
            proxy_pass http://foofoofoo.com; 
    }
}

请注意,proxy.conf包含在if语句之外.

版:

[Nginx@hip1 ~]$Nginx -v
Nginx version: Nginx/1.2.6 

有关$args和$is_args变量的一些信息:

http://nginx.org/en/docs/http/ngx_http_core_module.html

阅读文档总是有用的,我刚刚发现$query_string与$args相同,所以我上面有$args,你也可以根据文档使用$query_string.

重要

然而,值得注意的是,If can be Evil!

因此要么彻底测试,要么使用上面链接中提供的建议以类似于那里提供的示例的方式更改位置语句中的URL,例如:

    location ~^/static/photos/.* {
        error_page 418 = @dynamicphotos;
        recursive_error_pages on;

        if ($is_args != "") {
            return 418;
        }

        # Your default, if no query parameters exist:
        ...
    }

    location @dynamicphotos {
        # If query parameters are present:
        rewrite ^/static/photos/(.*)$ /DynamicPhotoQualitySwitch/photos/$1  break;
        expires     7d;
        include /etc/Nginx/proxy.conf; 
        proxy_pass http://foofoofoo.com; 
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐