如何将 Nginx 重写为将非尾部斜杠设置为尾部斜杠

如何将 Nginx 重写为将非尾部斜杠设置为尾部斜杠

我在 Nginx 中的重写(重定向)规则上遇到了问题。

这是我当前的设置

location /new { rewrite ^/new/([^/.]+)/$ /new/index.php?id=$1 last; }
  1. www.mysite.com/new/33/ -> 没关系
  2. www.mysite.com/new/33 -> 未找到错误

所以,我的问题是:我想将非尾随斜线重定向到尾随斜线。

答案1

您需要/通过添加 使最后一个成为可选项?。例如:

rewrite ^/new/([^/.]+)/?$ /new/index.php?id=$1 last;

这一有用的资源关于正则表达式。

答案2

我将使用这个配置:

location ~ ^/new/([^/.]+)/?$ {
    try_files $uri $uri/ /new/index.php?id=$1;
}

这里我们已经用语句捕获了 URL 的所需部分location,然后使用try_files它首先尝试文件系统上现有的文件,如果没有任何匹配的文件,则将请求传递给index.php

$uri $uri/如果您不想检查现有文件,可以删除。

答案3

我使用以下配置:

/test/([^'.]+)$ /test/index.php?id=$1

我的网站为AndroidAPKsBox.com现在。关于非尾部斜杠的重定向,我在 php 文件中进行了此操作:

if(substr($_GET['id'], -1) != '/'){ //if no trailling slash then redirect!
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".get_bloginfo('url').'/test/'.$_GET['id'].'/');
exit();

相关内容