【问题标题】:Nginx proxy pass and url rewritingNginx 代理传递和 url 重写
【发布时间】:2013-07-01 04:38:49
【问题描述】:

仅当我在 url 中有 GET 参数(查询字符串)时如何触发此规则, 否则我将匹配别名。

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

【问题讨论】:

  • 你的意思是GET参数吗?例如/static/photos/photo1.png?size=small
  • 是的,请举个例子。
  • Christophe,由于您不接受答案,我认为该解决方案不适合您。 Nginx 很棒,所以我很乐意帮助解决您可能遇到的任何问题,如果您遇到任何问题,请告诉我。
  • @hoonto 实际上它解决了我的问题我只是忘记将您的答案标记为已解决谢谢
  • 哦,太好了,我很高兴听到这个消息。谢谢!

标签: nginx reverse-proxy


【解决方案1】:

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

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

或者第二种方法是像这样使用方便的 $is_args :

    if ($is_args != "") {  

请记住,在 两种 样式中,您需要在 if 和左括号之间放置一个空格; "if (" 不是 "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; 
    }

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 2014-04-15
    • 2012-05-19
    • 1970-01-01
    • 2018-05-06
    • 2014-02-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多