【问题标题】:Htaccess rewrite html,htm,php to each other to help transition pages to the same file extensionHtaccess 相互重写 html,htm,php 以帮助将页面转换为相同的文件扩展名
【发布时间】:2021-05-14 08:50:33
【问题描述】:

我目前有以下 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}/$1\.html -f [NC]
RewriteRule ^(.+?)(?:\.(?:htm))?$ /$1.html [L,NC,R=302]

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

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

【问题讨论】:

  • 您使用的是哪个版本的 Apache?这些是您使用的实际指令吗?
  • @MrWhite Apache 2.4.46,是的,这就是当前正在使用的相应地交换 html 和 htm。

标签: html .htaccess url-rewriting


【解决方案1】:
RewriteCond %{DOCUMENT_ROOT}/$1\.html -f [NC]

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

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

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

由于您在RewriteRule pattern 中设置了文件扩展名可选,因此正则表达式匹配所有内容,因此您将结束测试一切,而不仅仅是以.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}/$1.html -f
RewriteRule ^(.+)\.php$ /$1.html [NC,R=302,L]

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

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

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

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

【讨论】:

  • 这似乎工作得很好!感谢您的帮助。对于您的 SEO 评论,我正在转向 PHP 模板,希望将所有内容合并为 php 文件,由于多年来的一些混乱做法,我留下了大量的静态页面仍然是 .htm 创造了这场斗争。希望几周内不会有问题。
  • 您可以删除 RewriteRule 指令上的 R=302 标志(外部重定向)标志,以创建对所需文件的内部重写。然后用户不知道 重定向
猜你喜欢
  • 1970-01-01
  • 2015-04-25
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
  • 2016-11-23
  • 2015-02-26
相关资源
最近更新 更多