Nginx merge_slashes redirect

2019-05-06 10:50发布

问题:

I am using nginx in with my Java Application and my problem is that nginx is merging the slashes and I am unable to redirect my website to the correct version.

For instance:

   http://goout.cz/cs/koncerty///praha/

is merged to

   http://goout.cz/cs/koncerty/praha/

and then I am unable to recognized the malformed URL and perform the redirection.

I tried to set

   merge_slashes off;

and then:

    rewrite (.*)//(.*) $1/$2 permanent;

But this has no effect and the // stays in the URL.

How can I achieve this?

回答1:

Try this (untested):

merge_slashes off;
rewrite (.*)//+(.*) $1/$2 permanent;

It might cause multiple redirects if there are multiple groups of slashes though.

Like this:

http://goout.cz/////cs/koncerty///praha/

Might go to:

http://goout.cz/cs/koncerty///praha/

Then finally:

http://goout.cz/cs/koncerty/praha/


回答2:

This works good, but for my setup adding port_in_redirect off; was necessary.



回答3:

We encounter the same problem because of mistake, we add two slashes on the URL, and nginx will return 301 error code for the url with two slashes.

The solution for me is:

Add merge_slashes off; to nginx.conf file, and in the location part, add rewrite (.*)//+(.*) $1/$2 break;

The location setting for me is like below:

    location / {
        rewrite (.*)//+(.*) $1/$2 break;
        proxy_pass http://http_urltest;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_buffers 4096 32k;
        proxy_buffer_size  32K;
        proxy_busy_buffers_size 32k;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

After add these two lines, when I access my url with two slashes, it will return the result with one slash.



回答4:

Try this(both nginx only and nginx with openresty configuration) you can improve site SEO by doing these 301 redirection

please keep this code inside the server section for your nginx site conf file

server {

........
........

set $test_uri $scheme://$host$request_uri;
if ($test_uri != $scheme://$host$uri$is_args$args) {
    rewrite ^ $scheme://$host$uri$is_args$args? permanent;
}

location {
    ................
    ................
}

}

its working good for me and am using this code now

example:-

request url- http://www.test.com//test///category/item//value/

result url:- http://www.test.com/test/category/item/value/

301 redirection so that the SEO of the site will not goes down