Nginx 301 redirect if string is given

jonathan maderer asked:

I would like to create a permanent redirect for specific querys inside my nginx server block. As example on my current url links to the php script have been: 

So i need to change this to
Is there a way to redirect permanent only if the parameter ?hash= is given inside the query and leave all other querys how they are?

Edit: I did some testings with this here

        location ~* /.*hash\=.*/ {
     rewrite ^$request_uri? permanent;

but Sadly this is also not working

My answer:

This is pretty simple. Just check for the existence of the argument.

location / {
    if ($arg_hash) {
        return 301 /folder/$is_args$args;

    # everything else...

Note here, that $is_args returns a ? if there is a query string, and an empty string otherwise. And $args returns the entire query string.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.