Forum Moderators: phranque

Message Too Old, No Replies

Htacess Help with Forcing Trailing Slashes

Forcing trailing slashes

         

Khem

11:11 am on Feb 4, 2011 (gmt 0)

10+ Year Member



Hi,

I was wondering if someone could point me in the right direction on how to correct an issues im having when I force trailing slashes.

Im quite new to Htacess - so apologies if it’s something obvious I have missed out.

I need to force a trailing slash after all folders - which seems to work no problem, but i don’t want to have the trailing slash after an actual page with an extension (example.php)

The code im using works fine at root level - but any pages deeper down end up being returned with a trailing slash.

For example www.example.com/folder/folder/page.php/

Where as I need to it to return www.example.com/folder/folder/page.php

I couldn’t seem to find the exact same problem while searching the forums so any headers would be great.

The current code im using is:

#RewriteBase /
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_URI} !index.php
#RewriteCond %{REQUEST_URI} !(.*)/$
#RewriteRule ^(.*)$ http://www.example.com/$1/ [L,R=301]

Many thanks in advance for any advice.

Jay

Khem

12:22 pm on Feb 4, 2011 (gmt 0)

10+ Year Member



Hi Again,

Just wanted to say that i have managed to get it working by adding this in:

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_URI} !/folder/([A-Za-z0-9-]+).php
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.example.com/$1/ [L,R=301]

and it seems to do the trick. As i said before, im still very green to all this - so if anyone has any advice on how i could have done it better - or cleaner i would be happy to learn.

Thanks again

Jay

g1smd

7:27 pm on Feb 4, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Make the "-f" check be very the last RewriteCond before the RewriteRule.

This ensures that the very slow disk read is invoked ONLY if ALL of the other conditions are true.

Khem

10:58 am on Feb 7, 2011 (gmt 0)

10+ Year Member



Many thanks for the tip and explanation. I shall amend this now.

jdMorgan

10:58 pm on Feb 7, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This could likely be simplified for efficiency:

RewriteBase /
# Externally redirect to add a trailing slash if the requested URL-path does not end with a slash and
# does not contain a period (i.e. a filetype) in the final URL-path-part
RewriteCond $1 !^([^/]+/)*[^./]*\.[^/]$
RewriteRule ^(.*[^/])$ http://www.example.com/$1/ [R=301,L]

Jim

Khem

10:19 am on Feb 16, 2011 (gmt 0)

10+ Year Member



Once again thank you for all the help - I really appreciate the explanation to go along with this as well - gives me something to research more.

Thanks

Jay