How to Remove Extensions From, and Force the Trailing Slash at the End of URLs?

Posted by Kronbernkzion on Server Fault See other posts from Server Fault or by Kronbernkzion
Published on 2010-03-18T23:06:18Z Indexed on 2010/03/18 23:11 UTC
Read the original article Hit count: 265

Example of current file structure:

example.com/foo.php
example.com/bar.html
example.com/directory/
example.com/directory/foo.php
example.com/directory/bar.html
example.com/cgi-bin/directory/foo.cgi

I want to remove HTML, PHP and CGI extensions from, and then force the trailing slash at the end of URLs. So, it could look like this:

example.com/foo/
example.com/bar/
example.com/directory/
example.com/directory/foo/
example.com/directory/bar/
example.com/cgi-bin/directory/foo/

I've searched for solution for 17 hours straight and visited more than a few hundred pages on various blogs and forums. I'm not joking. So I think I've done my research.

Here is the code that sits in my .htaccess file right now:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(([^/]+/)*[^./]+)/$ $1.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

As you can see, this code only removes .html (and I'm not very happy with it because I think it could be done a lot simpler). I can remove the extension from PHP files when I rename them to .html through .htaccess, but that's not what I want. I want to remove it straight. This is the first thing I don't know how to do.

The second thing is actually very annoying. My .htaccess file with code above, adds .html/ to every string entered after example.com/directory/foo/. So if I enter example.com/directory/foo/bar (obviously /bar doesn't exist since foo is a file), instead of just displaying message that page is not found, it converts it to example.com/directory/foo/bar.html/, then searches for a file for a few seconds and then displays the not found message. This, of course, is bad behavior.

So, once again, I need the code in .htaccess to do the following things:

  • Remove .html extension
  • Remove .php extension
  • Remove .cgi extension
  • Force the trailing slash at the end of URLs
  • Requests should behave correctly (no adding trailing slashes or extensions to strings if file or directory doesn't exist on server)
  • Code should be as simple as possible

I would very much appreciate any help. And to first person that gives me the solution, I'll send two $50 iTunes Store gift cards for US store. If this offend anyone, I am truly sorry and I apologize.

Thanks in advance. And sorry for such a long post.

© Server Fault or respective owner

Related posts about url-rewriting

Related posts about .htaccess