.htaccess在条件上使用多个斜杠



我试图在我的项目.htaccess的帮助下实现干净的URL。

我得到一个404时,我实现了一个条件与多个条件字符串likekeyword1/keyword2/param

所有其他条件,如RewriteRule ^home index.php [L,NC]工作良好

我的文件结构像

/subdirectory/
|-.htaccess
|-index.php
|-edit-user.php
|-new-user.php

我想要的干净的url是

mysite.com/subdirectory/user/edit/10

应该翻译成

mysite.com/subdirectory/edit-user.php?id=10

迄今为止我尝试过的一些最接近的解决方案(但没有运气)

RewriteRule (.*)/user/edit/([0-9]+)$ edit-user?id=$1 [L,NC]

RewriteBase /user/
RewriteRule ^user/edit/([0-9]+)$ edit-user.php?id=$1 [L,NC]

任何建议都非常感谢。

RewriteRule (.*)/user/edit/([0-9]+)$ edit-user?id=$1 [L,NC]

因为.htaccess文件在/subdirectory里面,所以你需要这样写指令:

RewriteRule ^user/edit/(d+)$ edit-user.php?id=$1 [L]

并删除任何RewriteBase指令。

d只是[0-9]的一个简写字符类。

RewriteRule模式匹配相对url路径(无斜杠前缀)。这是相对于包含.htaccess文件的目录。您还缺少要重写的文件名上的.php扩展名。您不需要NC标志,除非您确实希望允许混合情况的请求,但这可能会导致潜在的"重复内容"。这需要通过其他方式解决。

RewriteBase /user/
RewriteRule ^user/edit/([0-9]+)$ edit-user.php?id=$1 [L,NC]

实际上,您在这里非常接近,但是RewriteBase指令会导致此失败。RewriteBase指令的唯一目的是覆盖在相对路径替换上添加的目录前缀。RewriteBase指令设置了"url -path";(与文件系统路径相反)。

因此,在本例中,RewriteBase /user/将导致请求被重写为/user/edit-user.php?id=10(相对于根),根据您发布的文件结构,这显然是错误的。

如果没有定义RewriteBase,则将添加目录前缀,这导致重写相对于包含.htaccess文件的目录。

也不需要反斜杠-转义斜杠,因为正则表达式中没有斜杠分隔符。(围绕参数的空格是分隔符。)

所有其他条件,如RewriteRule ^home index.php [L,NC]工作良好

小心,因为这也将匹配/homeanything/home/something等。

最后发现问题。

My.htaccesswas

RewriteRule ^home  index.php [L,NC] RewriteRule ^([^.]+)$ $1.php [NC] 
RewriteRule ^user/edit/(d+)$ edit-user?id=$1 [L] 

(第一行添加.php到任何进来,第二行转换所需的URL)

这里发生的事情是,当我试图访问URLmysite.com/subdirectory/user/edit/10

第一条规则将其转换为mysite.com/subdirectory/user/edit/10.php而不是mysite.com/subdirectory/edit-user.php?id=10

这会导致404错误。

现在我改变了顺序,新的。htaccess文件看起来像,

RewriteRule ^admin/edit/(d+)$ edit-admin.php?aid=$1 [L]
RewriteRule ^([^.]+)$ $1.php [NC]

因此,当URL进入时,它将在与最后一个规则(附加.php)匹配之前检查所有其他规则,并将其转换为所需的结果。

教训:在。htaccess

中顺序很重要

最新更新