Forum Moderators: phranque

Message Too Old, No Replies

Forcing a backslash at end of url

         

ronearth

7:21 pm on Jul 29, 2004 (gmt 0)



Hi,

I am seeking way to force the backslash as the end of a url. For example, the correct form is:

[webmasterworld.com...]

If someone enters
[webmasterworld.com...]
without the last slash they are redirected to

[webmasterworld.com...]

Some browsers seem to do this automagically but at least one version of IE doesn't.

I have access to .htaccess.

Thank you in advance

TheBlueEyz

7:24 pm on Jul 29, 2004 (gmt 0)

10+ Year Member



Hehe I needed this yesterday.

It took me 5 hours to hunt down the solution, so to spare you that agonizing waste of time, here it is for you and all posterity...


RewriteEngine on

# Set rewrite base to the base directory
RewriteBase /

# If the url is an existing directory
RewriteCond %{REQUEST_FILENAME} -d

# Don't rewrite the URI
RewriteRule ^.*$ - [L]

# If the URI does not end with a slash
RewriteCond %{REQUEST_URI}!/$

# and the URI does not contain a full stop (Example: index.html)
RewriteCond %{REQUEST_URI}!\.

# Rewrite the URI to have a trailing slash
RewriteRule (.+) /$1/ [R=301,L]

The only part that you actually NEED is the last three lines, but I included the preceding two in case you wanted to make sure you don't get actual directories redirected (httpd.conf takes care of those and doing it twice can cause an infinite loop OR they can cause you to get 404's).

jdMorgan

7:43 pm on Jul 29, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'd suggest a simplification of that:

# If the url is not an existing directory
RewriteCond %{REQUEST_FILENAME} !-d
# and the URI does not contain a full stop (Example: index.html)
RewriteCond %{REQUEST_URI} !\.
# and if the URI does not end with a slash
RewriteCond %{REQUEST_URI} !/$
# Rewrite the URI to have a trailing slash
RewriteRule (.+) /$1/ [R=301,L]

If you wish this to apply to the root directory index when requested as "http://domain.com", then change the pattern in the rule to "(.*)"

Jim

TheBlueEyz

9:14 pm on Jul 29, 2004 (gmt 0)

10+ Year Member



Excellent, thanks Jim :)

g1smd

10:14 pm on Jul 29, 2004 (gmt 0)

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



By the way, a backslash is a \ and you don't want those in URLs at all. That is an error that you really want to avoid.

URLs always use a normal forward / slash.