Page 1 of 1

Handling Trailing Slashes In RewriteRule

Posted: Wed Sep 09, 2009 1:37 pm
by ggwarpig
I like trailing slashes. I think they are nice. But why do they hate me?

This works perfect as long as I include a trailing slash like mysite.com/profile/username/

Code: Select all

RewriteRule ^profile/(.*)/$ /profile/index.php?username=$1 [NC,L]
If I do not include the trailing slash I get a 404 error.
I would like to just 301 redirect anyone who forgets the slash to the url containing the slash.

Code: Select all

RewriteRule ^profile/(.*)$ /profile/$1/ [R=301,L]
Throwing this above the other rule put me in an infinite loop.

Any other ideas?

Re: Handling Trailing Slashes In RewriteRule

Posted: Wed Sep 09, 2009 1:41 pm
by Darhazer
The poll is unnecessary.
You can define the trailing slash as optional

Code: Select all

RewriteRule ^profile/(.*)(/?)$ /profile/index.php?username=$1 [NC,L]
Or you can create a rule for redirection, when there is no trailing slash

Re: Handling Trailing Slashes In RewriteRule

Posted: Wed Sep 09, 2009 1:47 pm
by ggwarpig
This change gave me a 500 Error with AND without the slash:

Code: Select all

RewriteRule ^profile/(.*)(/?)$ /profile/index.php?username=$1 [NC,L]
Why was my redirect rule throwing me in a loop?

Re: Handling Trailing Slashes In RewriteRule

Posted: Wed Sep 09, 2009 3:14 pm
by ggwarpig
Awesome. Got it working to handle both with & without the trailing slash. If there is no trailing slash, it redirects forcing the slash, otherwise it just rewrites. Your explanation of how to add an optional slash with (/?) helped me to understand this better. Thanks.
Final code

Code: Select all

RewriteRule ^profile/([^/]+)$ /profile/$1/ [R=301,L]
RewriteRule ^profile/([^/]+)/$ /profile/index.php?username=$1 [NC,L]