【发布时间】:2014-02-03 08:07:56
【问题描述】:
我目前有一个网站,其中有www.website.com/about.html。
但是,如果我在 url 中输入www.website.com/about/,它会出现默认的错误 404 页面。
我在某处看到了有关编辑 htaccess 文件的内容,但我不知道该怎么做。
【问题讨论】:
标签: html regex apache .htaccess mod-rewrite
我目前有一个网站,其中有www.website.com/about.html。
但是,如果我在 url 中输入www.website.com/about/,它会出现默认的错误 404 页面。
我在某处看到了有关编辑 htaccess 文件的内容,但我不知道该怎么做。
【问题讨论】:
标签: html regex apache .htaccess mod-rewrite
只需在您的 htaccess 顶部添加这一行,以减少您的 URL 扩展:
Options +MultiViews
或者,如果您更喜欢 mod_rewrite,则在您的 DOCUMENT_ROOT/.htaccess 文件中使用此代码:
RewriteEngine On
# To externally redirect /dir/file.html to /dir/file
RewriteCond %{THE_REQUEST} \s/+(?:index)?(.*?)\.html[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]
# To internally forward /dir/file to /dir/file.html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.+?)/?$ /$1.html [L]
【讨论】:
/about/
是一个目录。服务器上的哪个将调用该目录中的 index.* 文件。
直接调用 /about.html。或者(更优雅地)将 index.*(可以是 html php 什么都可以)放入 /about/ 中。
【讨论】:
www.website.com/about.html 正在引用一个名为 about.html 的文件,该文件存储在您的应用程序的根文件夹中。
当您尝试访问www.website.com/about/时,意味着您正在尝试访问应用程序中名为“about”的文件夹中的文件。你的解决方案中没有它,你会得到一个错误。
所以你访问它的方式是错误的。
尝试使用以下代码删除 .html 并访问您尝试访问的文件
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.html$ /$1 [L,R=301]
由于您想从应用程序 url 中删除 .html,因此无需在导航链接中写入 .html,例如,
<a href="http://www.website.com/about">about</a>
【讨论】:
正如 anubhava 所提到的,您可以在 .htaccess 文件的顶部添加这一行,以减少您的 URL 扩展名: 选项+MultiViews
但是您仍然必须以
的身份访问它www.website.com/about
因为
www.website.com/about/
您将转至 about 目录。希望这可以帮助。
【讨论】:
您需要为此在 Apache 配置文件中进行更改。这个问题已经在这里回答了: How to remove .html from URL
【讨论】: