Nginx merge_slashes redirect

2019-05-06 10:24发布

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?

4条回答
太酷不给撩
2楼-- · 2019-05-06 10:40

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

查看更多
何必那么认真
3楼-- · 2019-05-06 10:48

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楼-- · 2019-05-06 10:50

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

查看更多
SAY GOODBYE
5楼-- · 2019-05-06 10:58

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/
查看更多
登录 后发表回答