How do I remove trailing slashes from a URL when using Apache's default directory index file?

The Apache Rewrite Guide has a chapter on the "Trailing Slash Problem" (scroll down a bit) explaining how to solve the issue with the trailing slashes in general.

However, they also state that the trailing slash is required for directories when the rendered page in it uses resources (images, stylesheets, ..) with relative links - which will not work without the slash:

"The solution to this subtle problem is to let the server add the trailing slash automatically. To do this correctly we have to use an external redirect, so the browser correctly requests subsequent images etc. If we only did a internal rewrite, this would only work for the directory page, but would go wrong when any images are included into this page with relative URLs, because the browser would request an in-lined object. For instance, a request for image.gif in /~quux/foo/index.html would become /~quux/image.gif without the external redirect!"


You could always use mod_rewrite to redirect the directory name without the trailing slash to dirname/index.html. You could use RedirectConds to make sure that redirection doesn't get done if the URL ends with a trailing slash or with .html, and that it only applies specifically to blog post URLs.

Let me whip up an example, this'll take a moment.

# Trailing slashes and .html suffix
RewriteCond !/$
RewriteCond !\.html$

# Check if it's actually a dir and if index.html exists
RewriteCond %{REQUEST_URI} -d
RewriteCond %{REQUEST_URI}/index.html -f

# Rewrite anything that gets through (Probably insecure, but you get the idea)
RewriteRule ^(.*)$ $1/index.html

Edit: Can also be combined with Matt's solution of adding the redirect error code to the RewriteRule. It should probably also be made the last RedirectRule. Refer to the mod_rewrite documentation for more.


Removing index.php from URL can be done by writing only two lines in your .htaccess (mod_rewrite in Apache) file. Before writing the rules in .htaccess, make sure that mod_rewrite is enabled (RewriteEngine On) in your Apache server. Most probably mod_rewrite is enabled in a Linux server, but for a windows server you might need to contact the hosting people to enable mod_rewrite. You can check this by looking in phpinfo().

Below are the rules which will remove index.php from the URL:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /([^/]+/)*index.php HTTP/ 
RewriteRule ^(([^/]+/)*)index.php$ http://www.%{HTTP_HOST}/ [R=301,NS,L]

Redirect 301 means "Moved Permanently" so most search engines will remove index.php from the URL.