Htaccess 相互重写 html,htm,php 以帮助将页面转换为相同的文件扩展名

Htaccess rewrite html,htm,php to each other to help transition pages to the same file extension

我目前有以下 htaccess 项目,它们来回交换 html 和 htm 文件扩展名,所以如果您尝试加载 index.html 但唯一存在的文件是 index.htm 它将代替它。反之亦然。

目标是将所有内容都移动到 PHP,但与此同时是否可以将其扩展到涵盖 php。因此,如果其中一个较旧的 html 页面调用 index.htm 或 index.html,它会发现它们不存在并改为提供 index.php。同样,如果您键入 index.php 但它不存在,它将提供 htm 或 html 文件。

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/\.html -f [NC]
RewriteRule ^(.+?)(?:\.(?:htm))?$ /.html [L,NC,R=302]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/\.htm -f [NC]
RewriteRule ^(.+?)(?:\.(?:html))?$ /.htm [L,NC,R=302]

.htaccess: rewrite .htm urls internally to .php, but also redirect .php urls to .htm类似,但稍微复杂一些。

RewriteCond %{DOCUMENT_ROOT}/\.html -f [NC]

使用 -f 时不支持 NC 标志。虽然这不是“错误”(该标志被简单地忽略),但您的错误日志很可能充满 warnings.

也不需要反斜杠转义 TestString 中的文字点(RewriteCond 指令的第一个参数)。这被评估为普通字符串,而不是正则表达式。

RewriteRule ^(.+?)(?:\.(?:htm))?$ /.html [L,NC,R=302]

由于您在 RewriteRule 模式 中设置了文件扩展名 可选 ,因此正则表达式匹配 everything,因此您最终将测试 everything,而不仅仅是以 .htm 结尾的 URL(在本例中)。例如。请求 /foo.htm 和上面的测试 /foo.html 是否存在(好),但是请求 /foo.php 并且它测试 /foo.php.html 是否存在(不必要)。

您应该检查每个规则中的特定扩展名。

您想要检查每个文件扩展名,而不对任何文件进行优先排序。最好(更简单、更高效并且可以说是更好的 SEO)在请求中不使用任何文件扩展名并优先考虑您想要提供的文件扩展名。例如。请求 /foo 并服务 .php(如果存在),否则 .html,否则 .htm。无论如何,这不是你在这里问的。

解决方案与您已经完成的类似,您只需要有条不紊地测试每个组合即可。如果请求已经映射到现有文件,您还可以使用优化并跳过所有检查。

尝试以下操作:

# If the request already maps to a file then skip the following "5" rules
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [S=5]

# ----------
# Request .php, test .html
RewriteCond %{DOCUMENT_ROOT}/.html -f
RewriteRule ^(.+)\.php$ /.html [NC,R=302,L]

# Request .php, test .htm
RewriteCond %{DOCUMENT_ROOT}/.htm -f
RewriteRule ^(.+)\.php$ /.htm [NC,R=302,L]

# ----------
# Request .html (or .htm), test .php
RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^(.+)\.html?$ /.php [NC,R=302,L]

# Request .html, test .htm
RewriteCond %{DOCUMENT_ROOT}/\.htm -f
RewriteRule ^(.+)\.html$ /.htm [NC,R=302,L]

# ----------
# Request .htm, test .html
RewriteCond %{DOCUMENT_ROOT}/\.html -f
RewriteRule ^(.+)\.htm$ /.html [NC,R=302,L]