18

I've successfully modified my .htaccess file to remove trailing slashes on most pages but I'm wondering how to exempt my home page/directory? For example:

domain.com/test/ successfully redirects to domain.com/test

HOWEVER, when I hit my domain it will append the root document

domain.com/ redirects to domain.com/index.php

Is there a condition that I can add to ignore root url trailing slash so that it doesn't attempt to remove the trailing slash and add my default script? Here's what I have so far:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.+)/$
RewriteRule ^(.+)/$  /$1 [R=301,L]
Dan
  • 1,450
  • 3
  • 12
  • 18

3 Answers3

29

OK. After a bunch of trial and error I answered my own question.

The third line denotes that there has to be something in the URI in order to perform the redirect thus not redirecting if the url just contains the initial slash.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} (.*)$
RewriteRule ^(.+)/$ http://www.domain.com/$1 [R=301,L]
Dan
  • 1,450
  • 3
  • 12
  • 18
  • 5
    Instead of `http://www.domain.com/$1` you can use `http://www.%{HTTP_HOST}/$1` better. So user don't need to edit that line and make possible errors. – Code Guru Sep 25 '13 at 07:41
  • 2
    @YH's solution does not work for websites in subdirectories (nor for localhost, which cannot have `www.` before itself). So e.g. `localhost/web1/page1/` is redirected in a wrong way to `www.localhost/page1`. – Martin Pecka Nov 17 '13 at 16:32
17

Redirects request for all URLs ending in a / except for the root:

RedirectMatch 301 ^(.+)/$ $1
Greg Perham
  • 1,835
  • 1
  • 17
  • 26
9

How about

RewriteEngine On
RewriteRule ^(.*)/$ http://%{HTTP_HOST}/$1 
animuson
  • 53,861
  • 28
  • 137
  • 147
Antagonist
  • 612
  • 4
  • 17