首页 > 解决方案 > Apache 重定向,用于在末尾添加缺少的 .html

问题描述

我想将没有最后一段的任何请求重定向到 .html

例子:

/travels/
/travels.html
/travels/categories/new-zealand
/travels/categories/main.js

第 2 行和第 4 行不应重定向,而第 1 和 3 行应重定向到:

/travels.html
/travels/categories/new-zealand.html

我已经有了这个似乎可以用于捕获的正则表达式:^(https?:\/\/.+(\..+)*\/)?[^\s.]+$

我该如何准确地进行此重定向?我有一个带有正在运行的 apache werbserver 的虚拟服务器,并且启用了 mod_rewrite。rewrite 语句的外观如何,我应该把它放在哪里?如果我把它放在一个 .htaccess 文件中,我在哪里保存它?在页面的根目录内还是在任何地方?

标签: apache.htaccessmod-rewrite

解决方案


您无法匹配规则模式中的主机和 https 标头。您只能匹配RewriteRule. 要检查您需要使用的主机和 https 标头RewriteConds

 RewriteEngine on
# URL scheme is HTTPS
 RewriteCond %{HTTPS} on
# Host is www.example.com or example.com
 RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
#URL path is /travels/ then redirect the request to /travels.html
 RewriteRule ^/?travels/$ /travels.html [R,L]

这将重定向https://example.com/travels/https://example.com/travels.html . 这会将浏览器中的 URL 从旧 URL 更改为新 URL,如果您希望重定向在内部发生,则只需删除该R标志。


推荐阅读