Rewrite with $request_uri auto appends args

I’ve been using the following code to redirect non-www to www-refixed
domains:

server {
    server_name example.com;
    rewrite ^ http://www.example.com$request_uri permanent;
}

However, I just realized that when there is a query string, the
resulting URI has the query string twice. For example:

http://example.com/test.html?a=1&b=2

…is rewritten as:

http://www.example.com/test.html?a=1&b=2?a=1&b=2

Is this the correct behavior?

I can add a ‘?’ to the end of $request_uri to make it work as expected,
but I’ve never seen that in any examples, and I didn’t think rewrite was
supposed to auto-append the arguments unless I explicitly put arguments
on the replacement side.

I’m running Nginx 0.8.52.

Posted at Nginx Forum:

Hello!

On Fri, Nov 05, 2010 at 01:08:47PM -0400, NCRonB wrote:

However, I just realized that when there is a query string, the
resulting URI has the query string twice. For example:

http://example.com/test.html?a=1&b=2

…is rewritten as:

http://www.example.com/test.html?a=1&b=2?a=1&b=2

Is this the correct behavior?

Yes. Variable $request_uri contains args, while rewrite without
trailing ‘?’ will add args.

I can add a ‘?’ to the end of $request_uri to make it work as expected,
but I’ve never seen that in any examples, and I didn’t think rewrite was

Classic “redirect everything” example contains ‘?’. See e.g.
here:

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

: server {
: listen 80;
: server_name nginx.org;
: rewrite ^ http://www.nginx.org$request_uri?;
: }

supposed to auto-append the arguments unless I explicitly put arguments
on the replacement side.

rewrite is expected to preserve original args in all cases (either
preserve as is, or append if you added other arguments) unless you
specified trailing ‘?’.

Maxim D.

Classic “redirect everything” example contains
‘?’. See e.g. here:

Converting rewrite rules

: server {
: listen 80;
: server_name nginx.org;
: rewrite ^ http://www.nginx.org$request_uri?;
: }

Well, it sure does. Pitfalls and Common Mistakes | NGINX does
not show the ‘?’ and I (think) I’ve read many other configurations that
don’t have it, but perhaps I’m just getting old.

rewrite is expected to preserve original args in
all cases (either
preserve as is, or append if you added other
arguments) unless you
specified trailing ‘?’.

Got it. However, if you use $request_uri, doesn’t that always preserve
the original args by itself? I’m having trouble thinking of an example
where you would NOT want a question mark after $request_uri in a rewrite
statement.

Thanks!


Ron

Posted at Nginx Forum: