How to remove trailing slashes from URL with .htaccess?

Posted by Matt on Pro Webmasters See other posts from Pro Webmasters or by Matt
Published on 2011-12-14T23:22:48Z Indexed on 2012/10/06 15:53 UTC
Read the original article Hit count: 429

The situation

Across the entire domain, we'd like the URLs to hide file extensions and remove trailing slashes, independent of the domain name itself (as in, works on any domain).

Sample of our directory structure

We're not using index.* files except for the homepage.

  • /
    • /index.php
    • /account.php
    • /account
      • /subscriptions.php
    • /login.php
    • /login
      • /reset-password.php

The goal

Some examples of how these files might be requested, and how they should look in the browser:

  • / and index.php --> mydomain.com (literally just the bare domain name).

  • /account.php or /account/ or /account --> mydomain.com/account

  • /account/subscriptions.php or /account/subscriptions/ or /account/subscriptions --> mydomain.com/account/subscriptions

As you can see, there are several ways to access each webpage, but no matter which of the 2 or 3 ways you use to get there, it only shows the one preferred URL in the browser.

The question

How is this done with .htaccess using mod_rewrite?

I've banged my head against the wall trying to figure this out, but in general, the rewrite flow would seem to be something like this:

  1. External 301 redirect ( mydomain.com/account/ --> mydomain.com/account )
  2. Internally append .php ( mydomain.com/account --> mydomain.com/account.php )

I've been Googling this all day, read thousands of lines of documentation and config texts, and have tried several dozen times... I think more brains on this would help a lot.

UPDATE

We found an answer our question (see below).

© Pro Webmasters or respective owner

Related posts about apache

Related posts about htaccess