如何nginx重写设置非结尾斜杠到tracing斜杠

我在Nginx的rewrite(redirect)规则上遇到了问题。

这是我目前的设置

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

所以,我的问题是:我想redirect非尾随结尾斜杠。

你需要通过添加一个? 。 例如:

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

在正则expression式中查看这个有用的资源

我会使用这个configuration:

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

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

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

我使用configuration:

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

现在我的网站在AndroidAPKsBox.com 。 关于非tracing斜线的redirect我做了这个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();