如何对 .htaccess 重写规则进行例外处理?

How do you make an exception to a .htaccess rewrite rule?

我正在使用 .htaccess 重写以从我的网站中删除“.html”扩展名。但是,我在函数中使用 URL 将参数传递给另一个页面 (mysite.com/locations#12345)

我的重写规则如下:

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

我试过这样做:

RewriteCond %{THE_REQUEST} /locations/([^.]+) [NC]
RewriteRule ^ /locations%1 [NC,L,R]

但是我得到“mysite.com/locations%20HTTP/2#12345”

您需要关闭 DirectorySlash 以关闭目录的尾部斜杠,此外关闭 Indexes 以避免列出目录内容。

DirectorySlash Off
Options +FollowSymLinks -MultiViews -Indexes

RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+([^.]+)\.html[?\s] [NC]
RewriteRule ^ /%1 [L,R=302]

RewriteCond %{DOCUMENT_ROOT}/.html -f
RewriteRule ^(.+?)/?$ .html [L]

确保在清除浏览器缓存后进行测试。