2

我有一个非常有趣的行为。我想避免在我的网站上的 URL 中使用斜杠。我已将rewrite ^/(.*)/$ /$1 permanent;规则放入我的服务器块中,因此
https://example.com/something/
https://example.com/something////
重定向到
https://example.com/something

https://example.com/
重定向到
https://example.com

但是https://example.com////被重定向到... https://enjoygifts.ru////(实际上没有重定向,它是 200 代码)。为什么?

这是我的服务器块:

    服务器 {
        听 443 ssl;
        ...
        ... ssl 指令
        ...

        根 /var/www/mysite.com;
        索引 index.php;
        server_name mysite.com;
        重写 ^/(.*)/$ /$1 永久;

        地点 / {
            最后重写 ^/.*$ /index.php;
        }

        位置 ~ ^/index.php {
            try_files $uri =404;
            包括/etc/nginx/fastcgi.conf;
            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        }

        位置 ~ ^/storage/app/uploads/public { try_files $uri 404; }
        ...
        ...很多类似的位置块
        ...
    }

4

1 回答 1

2

https://example.com根本不存在,根 URI 是/- 它在浏览器地址栏中的显示方式取决于浏览器 - 有些会自动显示单独的/,而另一些会删除单独的/.

所以你不能重定向 from https://example.com/to https://example.com- 它会被默默地解释为重定向 from https://example.com/to https://example.com/

Nginx在评估和声明时使用规范化的 URI,并生成变量。多个连续出现的被折叠成一个.locationrewrite$uri//

尽管正则表达式^/(.*)/$与 URI 匹配//,但语句永远不会看到它。因为 Nginx 已经将该 URI 规范化为/,这与正则表达式不匹配。


如果带有多个/s 的根 URI 存在问题,请对变量应用正则表达式,该$request_uri变量包含规范化之前的原始 URI,还包括查询字符串(如果有)。

例如:

if ($request_uri ~ "^/{2,}(\?|$)") { 
    return 301 /$is_args$args; 
}

这可以放在你的location / {...}块内。请参阅此使用注意事项if

于 2018-11-06T11:15:02.417 回答