【发布时间】:2017-12-05 12:12:35
【问题描述】:
我想用 301 重定向所有不带斜杠的 url 重定向到带有斜杠的相同 url。如果不是文件夹或文件,我也想将所有 url 替换为 index.php。
我试图用以下代码做到这一点:
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~* .*[^/]$ {
try_files $uri $uri/ permanent;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-mysite-fpm.sock;
fastcgi_read_timeout 300;
}
第一个位置单独工作完美,但这些位置不能一起工作。它通常返回文件和文件夹,但是当请求没有斜杠的url时,nginx返回500错误,并且只返回文件index.php下载,当url带有斜杠时。
我也尝试用代码来实现:
location / {
try_files $uri $uri/ @addslash /index.php$is_args$args;
}
location @addslash {
rewrite ^(.+[^/])$ $1/ permanent;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-mysite-fpm.sock;
fastcgi_read_timeout 300;
}
但它可以在没有任何来自 url 的重定向的情况下工作,而无需尾部斜杠。
如何使重定向到斜杠和替换到 index.php?
【问题讨论】: