How to remove trailing slashes from a URL when using Apache’s default directory index file

apache-2.2rewrite

I am using Apache to serve a blog which consists of static HTML files. Currently, the blog uses a pretty standard URL structure, like this:

/2010/03/21/my-awesome-blog-post/

which maps to the file

/2010/03/21/my-awesome-blog-post/index.html

using Apache's mod_dir.

I'd like to remove the trailing slash so that URLs like

/2010/03/21/my-awesome-blog-post

work in the same way (and don't get redirected). Is there a way to do that with Apache?

(Note that I want URLs with the trailing slash to continue to work, as well.)

(Further note: I saw something about Apache's DirectorySlash directive, but I don't think it does what I want … although I'm not sure about that.)

Best Answer

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.