.htaccess 页面重写拼写错误



我正在构建一个内容管理系统,以允许公司员工按类别列出。从本质上讲,这就是我想要完成的目标:

有一个名为inside.php的页面包含 404、500 等错误。我们有一个名为physicians.php的页面,它传递变量并根据变量显示特定信息physicians.php?id=1以便显示特定类别的员工。目前,当您转到http://website.com/physicianshttp://website.com/physicians/时,它会重定向到http://website.com/physicians.php很好,但问题是即使您输入医生一词的某些变体,也会发生这种情况。例如,physiciansasfhouiae仍然会链接到我们希望它链接到inside.phpphysicians.php,因为它在技术上是一个不存在的页面。

这是我现在拥有的重写代码:

RewriteEngine on
#enables you to access PHP files with HTML extension
AddType application/x-httpd-php5 .html .htm
RewriteCond ${REQUEST_URI} ^.+$
RewriteRule ^detail/(css|js|img)/(.*)?$ /$1/$2 [L,QSA,R=301] [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]
RewriteCond %{REQUEST_URI} physicians
RewriteRule .* physicians.php
RewriteRule ^physicians/((([a-zA-Z0-9_-]+)/?)*)$    physicians.php?id=$1    [NC,L]
RewriteRule ^((([a-zA-Z0-9_-]+)/?)*)$ inside.php?page=$1

您应该首先删除以下 2 行:

RewriteCond %{REQUEST_URI} physicians
RewriteRule .* physicians.php

由于它们下方已经RewriteRule,这 2 行不仅不是必需的,而且它们导致了您注意到的主要问题。这 2 行匹配任何带有子字符串"医生"的 URL,这不是您想要的。因此,您需要使匹配模式更具体;值得庆幸的是,下一条RewriteRule行已经在这样做了:

RewriteRule ^physicians/((([a-zA-Z0-9_-]+)/?)*)$    physicians.php?id=$1    [NC,L]

这条线真的是你完成你想要的所需要的一切。它告诉Apache只匹配单词"physicians",如果它是URL的第一个单词并以斜杠结尾(即整个,确切的单词"physicians"),这与"physiciansasfhouiae"等拼写错误不匹配。

但作为建议,我会稍微调整一下它以使可选的尾部斜杠仍然匹配,并从 ID 参数中删除斜杠:

RewriteRule ^physicians(/((([a-zA-Z0-9_-]+)/?)*))?$    physicians.php?id=$4    [NC,L]

因此,这会将所有这些变体发送给医生.php:

/physicians
/physicians/
/physicians/abc123
/physicians/abc123/

ID 参数将等于abc123(如果提供)。所有其他请求都将转到 inside.php,即使 URL 包含"医生"的变体。

最新更新