0

我的 .htaccess 文件有一些问题,我在其中放置了删除文件扩展名的代码,所以它看起来像这样:www.foo.com/x,它适用于我的所有页面。但是,当我使用导航栏时,它不起作用。我已经将每个页面上的 URL 更改为 www.foo.com/x,所以我对我的问题可能是什么感到困惑。这是我的 .htaccess 文件中的代码:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.html$ /$1 [L,R=301]

这是我的导航条码:

 <ul id="menu">
            <li><a href="http://www.foo.com/" class="active">Home</a></li>
            <li><a href="http://www.foo.com/projects">Projects</a></li>
            <li><a href="http://www.foo.com/about">About</a></li>
            <li><a href="http://www.foo.com/contact">Contact</a></li>
 </ul>

我可能会添加 www.foo.com/projects 等工作正常并转到正确的页面,如果这不明显,我的 .htaccess 文件也在根文件夹中。

4

1 回答 1

1

Your original rules are going to cause a loop if you try to internally rewrite them back. For example, if you start off with the URI /some/file.html

  1. Browser requests /some/file.html
  2. RewriteRule ^(.*)\.html$ /$1 [L,R=301] matches, browser is redirected to /some/file
  3. Browser requests /some/file
  4. Internal rewrite to /some/file.html
  5. Rewrite engine loops, first rule matches again, browser is redirected to /some/file
  6. repeat from #3

So you need to match against the actual request for your first rule:

RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.html
RewriteRule ^ /%1 [L,R=301]

This does the redirect, in case you have links that still go to the .html files, now you need to internally rewrite them back to html files:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ /$1.html [L]

If all of your links already have the .html part removed, then you won't need the first rule at all.

于 2012-08-22T01:36:04.907 回答