【问题标题】:How do you make an exception to a .htaccess rewrite rule?您如何对 .htaccess 重写规则进行例外处理?
【发布时间】:2021-05-15 13:39:17
【问题描述】:

我正在使用 .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”

【问题讨论】:

  • 你的原始网址是什么,应该重定向什么网址?
  • 我正在请求“mysite.com/locations#12345”,但我使用的重写规则是重写它。如果我删除我的覆盖尝试,我当前的规则会将该 URL 设为“mysite.com/locations/#12345”-“/”不能存在,因为它会将我带到位置 / 目录而不是页面。跨度>
  • 您的原始规则只是从 URL 中删除 .html,但您在 mysite.com/locations#12345 中没有 .html
  • 即使我请求“mysite.com/locations.html#12345”,它也会被重写为“mysite.com/locations/#12345 - 请求使用或不使用“.html”会产生相同的重写前两个条件。
  • 如果locations 是一个真实目录,那么mod_dir 会自动添加一个斜杠。你有一个名为locations.html 的文件和一个名为locations/ 的目录吗?

标签: html apache .htaccess mod-rewrite url-rewriting


【解决方案1】:

您需要关闭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}/$1.html -f
RewriteRule ^(.+?)/?$ $1.html [L]

请务必在清除浏览器缓存后进行测试。

【讨论】:

  • 似乎有效!一件事......我网站上的光标不再更改为链接上的“指针”,光标保持默认。可用性方面的问题。知道为什么吗?
  • 对不起,这与服务器端无关,可能是我不知道的一些 css 样式问题
  • 不确定是什么原因造成的,因为我没有更改 CSS。大约 5 分钟后,光标问题消失了。奇怪的!我会将您的答案标记为已接受。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多