Christophe Debove
Christophe Debove

Reputation: 6286

Nginx proxy pass and url rewriting

How to trig this rule only when I have GET parameters(query string) in url, otherwise I will match on an alias.

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

Upvotes: 3

Views: 15891

Answers (1)

Matt Mullens
Matt Mullens

Reputation: 2256

The 1st way that I know of is using a regex against the $args parameter like so:

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

Or the 2nd way is to use the convenient $is_args like so:

    if ($is_args != "") {  

Remember that in both styles you need to put a space between the if and the opening parenthesis; "if (" not "if(" as well as a space after the closing parenthesis and the opening brace; ") {" rather than "){".

Full example using the 1st style above, 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; 
    }
}

Full example using the 2nd style above, 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; 
    }
}

Note that the proxy.conf include goes outside of the if statement.

Version:

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

And some info on the $args and $is_args variables:

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

Reading the docs is always useful, I just discovered that $query_string is the same as $args, so where I have $args above, you could also use $query_string according to the docs.

IMPORTANT

It is important to note however, that If can be Evil!

And therefore either test thoroughly or use the recommendation provided in the link above to change the URL inside location statement in a way similar to the example provided there, something like:

    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; 
    }

Upvotes: 8

Related Questions