Add or remove trailing slash in URL with .htaccess

If you`re using some kind of CMS, usually its normal that each URL works with or without trailing slash, e.g. these URLs would be the same:
http://example.org/about
http://example.org/about/

Still Google, Yahoo, MSN and other search engines treat them as different urls and gives penalty as they are dupliate URLs with identical content.
You have two options – to add or to remove the trailing slash. After a bit of reading I chose to remove the slash from my celica site, because I`m using Drupal CMS that removes trailing slashes for new content and I don`t really want to hack the CMS plugins. To alter the URLs, you need to edit .htaccess file at the root directory of your website ( http://example.org/.htaccess )
Add this code to your .htaccess file to remove trailing slashes:

#get rid of trailing slashes
RewriteCond %{HTTP_HOST} ^(www.)?turbocelica\.lv$ [NC]
RewriteRule ^(.+)/$ http://www.turbocelica.lv/$1 [R=301,L]

or use this code to ADD trailing slash to the end of each URL:

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

Make sure you backup your .htaccess file before you edit. It`s easy to get “500 Internal server error” if you don`t know what you`re doing ;)
Read more here: http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

Author: Valters Bože

abstract person

10 thoughts on “Add or remove trailing slash in URL with .htaccess”

  1. I’ve a link : subdomain.abc.com.vn/foulder/
    I want to change to : subdomain.abc.com.vn/foulder/

    The same with subdomain.abc.com.vn/foulder1/foulder2/ => subdomain.abc.com.vn/foulder1/foulder2

    Can you help me with .htaccess file, please?

  2. I’ve a link : subdomain.abc.com.vn/foulder/
    I want to change to : subdomain.abc.com.vn/foulder

    The same with subdomain.abc.com.vn/foulder1/foulder2/ => subdomain.abc.com.vn/foulder1/foulder2

    Can you help me with .htaccess file, please?

  3. Everybody wants to add a slash, you happily gave the solution to remove the ending slash. Worked out great.

  4. Those examples doesnt work fine on my end.

    I have this sample url:
    domain.com/baby/ , when i type this directly in the url the url must be domain.com/baby only and it / (slash) is removed. here is my current htaccess :

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond $1 !^(index\.php|(.*)\.swf|css|js|uploads|images|robots\.txt)
    RewriteRule ^(.*)$ /mumcentre/index.php?/$1 [QSA,L]
    ErrorDocument 404 /

    Will this work on my local?

Leave a Reply

Your email address will not be published. Required fields are marked *