Nginx代理传递和URL重写

Chr*_*ove 3 reverse-proxy nginx

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

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

hoo*_*nto 8

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

    if ($args ~ "^(\w+)=") { 
Run Code Online (Sandbox Code Playgroud)

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

    if ($is_args != "") {  
Run Code Online (Sandbox Code Playgroud)

请记住,在两种样式中,您需要在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; 
    }
}
Run Code Online (Sandbox Code Playgroud)

使用上面第二种风格的完整示例,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; 
    }
}
Run Code Online (Sandbox Code Playgroud)

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

版:

[nginx@hip1 ~]$ nginx -v
nginx version: nginx/1.2.6 
Run Code Online (Sandbox Code Playgroud)

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

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

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

重要

然而,重要的是要注意,如果可以是邪恶的!

因此,要么彻底测试,要么使用上面链接中提供的建议以类似于那里提供的示例的方式更改位置语句中的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; 
    }
Run Code Online (Sandbox Code Playgroud)