【问题标题】:Force trailing slash in .htaccess doesn't work.htaccess 中的强制斜杠不起作用
【发布时间】:2015-04-09 22:38:22
【问题描述】:

除了在子目录中包含一些 Wordpress 网站(本网站未引用)之外,不做任何事情,链接会自动从自身中去除 .html 结尾。我不知道为什么会这样,但这是我想要的选项。

现在,我在尝试在我的网站中强制使用斜杠时遇到了麻烦。我试过这个选项:

Options -Multiviews
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

我目前也将它用于 404 页面(参考 404.html):

ErrorDocument 404 /404

但是,当我尝试访问一个页面时,例如http://bluecocoa.com/time/,我收到了重定向无限循环错误。我使用http://redirectdetective.com 跟踪重定向。我发现重定向是这样的:

http://bluecocoa.com/time --> http://bluecocoa.com/time/ --> http://bluecocoa.com/404 --> http://bluecocoa.com/404/ --> http://bluecocoa.com/404 --> http://bluecocoa.com/404/ --> infinite loop

对我来说,它看起来像是通过添加一个来修复没有尾部斜杠的页面。由于某种原因,没有找到带有斜杠的页面,它重定向到 404。404 导致无限重定向。

我的网站目录如下所示:

index.html
time.html
/mtc/ [a wordpress directory]
/posts/
blog.html
etc...

对于解决这些问题的任何帮助将不胜感激!

【问题讨论】:

  • /time/也是目录吗?
  • @JonLin 不,这是一个 .html 文件
  • 添加 .html 的规则是什么?
  • @JonLin 这是让我感到困惑的另一件事。我没有添加任何规则来删除结尾。出于某种原因,GoDaddy 或 WordPress 子目录中的 htaccess 将其删除?

标签: apache .htaccess redirect


【解决方案1】:

有这些规则可以在你的根目录.htaccess 中隐藏.html 扩展:

Options -MultiViews
RewriteEngine On
RewriteBase /

# To externally redirect file.html to /file/
RewriteCond %{THE_REQUEST} \s/+(.+?)\.html[\s?] [NC]
RewriteRule ^ /%1/ [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=302,NE,L]

# To internally forward /file to /file.html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.html -f [NC]
RewriteRule ^(.+?)/?$ $1.html [L]

【讨论】:

  • 效果很好!但是还有一个问题。我有这样引用的 CSS 文件和图像:css/style.css。当我添加您的调整时,一切正常,除了图像、css 和 javascript 都是断开的链接。有什么想法吗?
  • 要解决该问题,请在页面 HTML 的 <head> 部分添加此代码:<base href="/" />,以便从该 URL 而非当前页面的 URL 解析每个相对 URL。
猜你喜欢
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 2017-07-16
  • 1970-01-01
  • 2022-07-22
  • 2017-06-15
相关资源
最近更新 更多