php - htaccess 为带或不带尾部斜杠的 url 添加 .html 扩展名

标签 php apache .htaccess redirect mod-rewrite

首先,我有一个自定义 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-textdomain.com/slug-text/ 重定向到 domain.com/slug- text.htmlslug-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-textdomain.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/

相关文章:

php - 如何在 Mac 上安装多个 xampp?

php - 在 apache tomcat 服务器上使用 CakePHP

php - .htaccess 可选字符?

php - 显示第一个选中的行 Mysql

php - 如何从输入流中获取字符串值?

用于插入的 php 数组内爆

java - 无法将 apache 转发到端口 8080

php - Laravel 请求按名称合并

java - 如何使用多个参数调用 HTTP POST 请求?

php - 超过 30 秒的最大执行时间