第 1 步。
更改所有链接以从链接中删除 .html。确保您已关闭 Multiviews:
Options -Multiviews
第 2 步。
当主机名中缺少 www 时,您需要规则来重定向浏览器:
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
第 3 步。
当使用 .html 或 .php 请求 URL 并删除扩展名时,您需要规则来重定向浏览器:
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /([^\ ]+)\.(php|html?)
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ /%2 [L,R=301]
第 4 步。
如果请求实际上是针对 php 或 html 文件的,您需要规则来在内部重写 URI:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ /$1.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.htm -f
RewriteRule ^(.*)$ /$1.htm [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ /$1.html [L]
.htaccess
总而言之,您的 htaccess 中应该有这些规则(放弃您可能已经尝试解决此问题的任何规则):
# Make sure Multiviews is off
Options -Multiviews
# turn on rewrite engine
RewriteEngine On
# Redirect requests that are missing www and not a subdomain
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
# Redirect if requests is for a .htm, .html, or .php
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ /([^\ ]+)\.(php|html?)
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ /%2 [L,R=301]
# rewrite to the proper extension if such a file exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ /$1.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.htm -f
RewriteRule ^(.*)$ /$1.htm [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ /$1.html [L]
完全是这样:
- 如果浏览器 URL 地址栏显示:http://example.com/index.html,它将被重定向到 http://www.example.com/index
- 如果浏览器 URL 地址栏显示:http://www.example.com/index,则会显示 http://www.example.com/index 的内容。 html(或
index.php,如果存在)。地址栏保持不变。
- 如果浏览器 URL 地址栏显示:http://foo.example.com/images/image.png,您将在
/images/image.png 看到图像。地址栏保持不变。
- 如果浏览器 URL 地址栏显示:http://foo.example.com/path/foo/bar.php,它将被重定向到 http://foo.example。 com/path/foo/bar
- 如果浏览器 URL 地址栏显示:http://foo.example.com/path/foo/bar,它将显示 http://foo.example 的内容。 com/path/foo/bar.php。地址栏保持不变。