2

I am trying to implement a simple custom redirect with nginx.

Incoming request:

http://localhost:8182/testredirect/?asd=456&aaa=ddd&trueurl=http://example.com/sdd?djdj=55

I would like to receive HTTP 302 redirect to http://example.com/sdd?djdj=55. I.e forward to anything after trueurl argument.

I try this:

location /testredirect/ {
    rewrite "\&trueurl=(.*)$" $1 redirect;
}

But this does not seem to work. It returns error 404. Do I miss something?

baldr
  • 2,891
  • 11
  • 43
  • 61
  • I'd try `rewrite "\&trueurl=http://(.*)$" http://$1 redirect;` instead. `nginx` behaves differently if the second argument of `rewrite` starts with `http://` or `https://` – grochmal Jun 12 '16 at 01:40

2 Answers2

2

The rewrite regex does not operate on the query string part of the URI, so your code will never match. However, the parameter in question has already been captured as $arg_trueurl. See this document for details.

For example:

location /testredirect/ {
    return 302 $arg_trueurl;
}
Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • This makes sense, but unfortunately `trueurl` can contain unescaped arguments too. I need to parse query string by regex to extract anything after `&trueurl=` and redirect to it. – baldr Jun 12 '16 at 11:22
1

Thanks @richard-smith for the helpful note about query string. Finally I ended up with the following:

location /testredirect/ {
    if ($args ~* "\&trueurl=http(.*)$") {
        return 302 http$1;
    }
}
baldr
  • 2,891
  • 11
  • 43
  • 61