Owen
Owen

Reputation: 593

What's the correct nginx rewrite expression for this URL pattern?

I'm going bananas trying to get a Nginx rewrite rule to work. An example URL that the rewrite pattern should match is:

https://test.mydomaind.com/abc.php?id=1

My rewrite rule:

rewrite ^/abc\.php?id=(.*)$ https://test.mydomain.com/page/$1 permanent;

But this returns a 404 with the example URL.

Can anyone tell me what I'm doing wrong? When I leave out the query string parameter in the condition the rewrite does work and the user is redirected 301:

rewrite ^/abc\.php$ https://test.mydomain.com/page permanent; # THIS WORKS

Any help is greatly appreciated!

Upvotes: 0

Views: 921

Answers (1)

Richard Smith
Richard Smith

Reputation: 49702

Anything from the ? onwards is the query string and is not considered when matching the URI to locations or rewrite statements.

The query string (or arguments) are accessible in the $request_uri and $query_string (aka $args) variables and the family of variables prefixed with $arg_.

You could implement something similar with:

location = /abc.php {
    return 301 https://test.mydomain.com/page/$arg_id;
}

If you need to test for the presence of an id= argument, you will need to resort to map or if statements.

Upvotes: 2

Related Questions