Matthew Brzezinski
Matthew Brzezinski

Reputation: 1794

.htaccess removal of extensions

I'm having some troubles with my .htaccess file, I have code placed in which removes the extensions of files so it looks like this: www.foo.com/x and it works fine for all of my pages. However, when I use my navigation bar it doesn't work. I've already changed the URLs on each page to www.foo.com/x, so I'm confused as to what my problem could be. Here's the code in my .htaccess file:

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

And here's my nav-bar code:

 <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>

I might add that www.foo.com/projects, etc. works fine and goes to the correct page also my .htaccess file is in the root folder if that wasn't obvious.

Upvotes: 0

Views: 119

Answers (1)

Jon Lin
Jon Lin

Reputation: 143886

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.

Upvotes: 1

Related Questions