2013-06-25 85 views
3

如何仅当我在URL中具有GET参数(查询字符串)时触发此规则,否则我将匹配一个别名。Nginx代理传递和URL重写

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

您是指GET参数吗?例如/static/photos/photo1.png?size=small – GCon

+0

是的,请举例说明。 – Nicholas

+0

Christophe,由于您没有接受答案,我认为该解决方案对您无效。 Nginx非常棒,所以我很乐意帮助解决您可能遇到的任何问题,只要告诉我您是否遇到任何问题。 – hoonto

回答

8

,我知道的是使用正则表达式在$ args参数,像这样的1路:

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

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

if ($is_args != "") { 

请记住,在两个风格你需要在if和左括号之间放一个空格; “if(”not“if(”以及右括号和左括号之后的空格;“){”而不是“){”。

使用1号风格上面,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语句。

版本:

[[email protected] ~]$ 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; 
    }