首先,我有一个自定义 url 重写,它将请求变量发送到 php 脚本
重写规则如下:
RewriteRule ^([\w\/-]+)(\?.*)?$ test/index.php?slug=$1 [L,T=application/x-httpd-php]
因此,如果您访问诸如 domain.com/slug-text
之类的内容,它会将 slug-text
发送到位于名为的文件夹中的 index.php
测试。
我想要的是我的所有网址看起来像 domain.com/slug-text.html
,但 slug-test
变量仍应发送到 index.php
文件。
还有
我不明白的是重定向。我希望所有旧网址从 domain.com/slug-text
或 domain.com/slug-text/
重定向到 domain.com/slug- text.html
和 slug-text
发送到位于测试文件夹中的 index.php
文件。
搜索了很多,但在互联网上找不到这个问题的答案。
谢谢大家的帮助。
更新: 我的新代码是:
RewriteEngine On
Options +FollowSymlinks
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(([\w/\-]+)?[\w-])(?!:\.html)$ http://domain.com/$1\.html [L,R=301]
RewriteRule ^(([\w/\-]+)?[\w-])(/|\.html)?$ test/index.php?slug=$1 [L]
domain.com/slug-text/
未重定向到 domain.com/slug-text.html
domain.com/slug-text
按照预期重定向到 domain.com/slug-text.html
我需要改变什么?
最佳答案
这条规则:
RewriteRule ^(([\w/\-]+)?[\w-])(/|\.html)?$ test/index.php?slug=$1 [L]
将捕获 domain.com/slug-text
、domain.com/slug-text/
和 domain.com/slug-text.html
并将 slug-text
发送到 /test/index.php
内的 slug
参数。
如果您确实想使用 [R=301]
从旧网址重定向到新网址,请使用以下命令:
RewriteRule ^(([\w/-]+)?[\w-])/?(?!:\.html)$ http://domain.com/$1.html [L,R=301]
RewriteRule ^(([\w/-]+)?[\w-])\.html$ test/index.php?slug=$1 [L]
另请注意,使用显式重定向时,底部规则会被修改为捕获以 .html
结尾的 url
还建议(如果您的 .htaccess 尚未包含此内容)过滤现有文件和文件夹的条件,以免被重定向规则捕获。只需在 RewriteRule
行之前添加这些行即可:
# existing file
RewriteCond %{SCRIPT_FILENAME} !-f
# existing folder
RewriteCond %{SCRIPT_FILENAME} !-d
如果使用符号链接(symbolic link):
# enable symlinks
Options +FollowSymLinks
# existing symlink
RewriteCond %{SCRIPT_FILENAME} !-l
//添加
您的 .htaccess 文件应如下所示:
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(([\w/-]+)?[\w-])/?(?!:\.html)$ http://domain.com/$1.html [L,R=301]
RewriteRule ^(([\w/-]+)?[\w-])\.html$ test/index.php?slug=$1 [L]
关于php - htaccess 为带或不带尾部斜杠的 url 添加 .html 扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682420/