首页 > 解决方案 > 重写 .htaccess 的规则

问题描述

我有一个关于 .htaccess 文件的基本问题。

目前我的包括:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301]

将所有链接重定向到网站的安全超文本传输​​协议 (https)。

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^/?([^\.]+)$ $1.html [L]

重写所有没有文件扩展名的 .html 文件。

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^/?(.+)/?$ /$1/index.html [L]
RewriteRule ^/?(.+/)index\.html$ /$1 [R=301]

从站点 URL 中删除 index.html。由于第二条规则,我应该删除文件扩展名 (.html) 吗?

ErrorDocument 404 /404.html

不言自明。我也应该在这里删除文件扩展名吗?

总的来说 -代码是否正确,这是我的 .htaccess 文件中的样子吗?

我感谢您的帮助。

标签: html.htaccesswebserverfrontend

解决方案


我最终使用了这段代码:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^/?([^\.]+)$ $1.html [L]

ErrorDocument 404 /404.html

从 URL 规则中删除 index.html没有用,因为我更改了 html 部分中的链接:

<a href="index.html">Homepage</a>

至:

<a href="/">Homepage</a>

和类比的:

<a href="en/index.html">English Homepage</a>

至:

<a href="en">English Homepage</a>

推荐阅读