Nginx $ request_uri has a duplicate request parameter

I found that nginx $ request_uri duplicates the request parameters.

The goal I want to achieve is to redirect any bare domain request to the www domain. Here is an example configuration.

server { listen 8080; server_name localhost; location / { if ($http_host !~* "^www\.") { rewrite (.*) http://www.$http_host$request_uri permanent; } } } 

As a result, I got the following:

 curl -I http://127.0.0.1:8080/pp/\?a\=b HTTP/1.1 301 Moved Permanently Server: nginx/1.6.2 Date: Thu, 22 Jan 2015 04:07:39 GMT Content-Type: text/html Content-Length: 184 Connection: keep-alive Location: http://www.127.0.0.1:8080/pp/?a=b?a=b 

The query parameter is duplicated as a result; Did I miss something?

+6
source share
2 answers

The replication of the query parameters you see is the expected behavior of Nginx. To change this, do you need to add trailing ? to rewrite, as in:

  server { listen 8080; server_name localhost; location / { if ($http_host !~* "^www\.") { rewrite (.*) http://www.$http_host$request_uri? permanent; } } } 

See the documentation here .

If the replacement string contains new query arguments, the arguments of the previous query are added after them. If this is undesirable, placing a question mark at the end of the replacement line avoids adding them, for example:

rewrite ^ / users /(.*)$/ show? user = $ 1? last;

However, the configuration presented by Alexey Deryagin is a better and more efficient option for your desired type of redirection, because each request will be evaluated by the if block in the original configuration, regardless of whether it is needed or not.

+9
source

if it’s evil (not always, but), so why not try returning 301:

 server { server_name example.com; return 301 $scheme://www.example.com$request_uri; } server { server_name www.example.com; root /var/www; location / { index index.html; } } 
+2
source

Source: https://habr.com/ru/post/981383/


All Articles