Handling Trailing Slashes In RewriteRule

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply

What do you think of trailing slashes?

I love them
1
50%
They are ok
0
No votes
I dont care
1
50%
They bug me
0
No votes
I hate them
0
No votes
 
Total votes: 2

ggwarpig
Forum Newbie
Posts: 7
Joined: Wed Sep 09, 2009 12:47 pm

Handling Trailing Slashes In RewriteRule

Post 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?
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Handling Trailing Slashes In RewriteRule

Post 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
ggwarpig
Forum Newbie
Posts: 7
Joined: Wed Sep 09, 2009 12:47 pm

Re: Handling Trailing Slashes In RewriteRule

Post 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?
ggwarpig
Forum Newbie
Posts: 7
Joined: Wed Sep 09, 2009 12:47 pm

Re: Handling Trailing Slashes In RewriteRule

Post 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]
Post Reply