Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing slash using .htaccess except for home / landing page

Tags:

.htaccess

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]
like image 982
Dan Avatar asked Nov 12 '10 17:11

Dan


People also ask

How do I get rid of trailing slash?

Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.

How do I get rid of trailing slash in WordPress?

To do so, go to the “Settings -> Permalinks” section and, depending on your situation, either add or delete the last slash. The “Custom Structure” field ends with a slash, so all other WordPress URLs will have the trailing slash.

How do I remove the last slash from a URL in Java?

String s = "http://almaden.ibm.com/"; s= s. replaceAll("/",""); and this: String s = "http://almaden.ibm.com/"; length = s.


1 Answers

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]
like image 104
Dan Avatar answered Sep 25 '22 09:09

Dan