Rich Coy
Rich Coy

Reputation: 545

Mod Rewrite Partial Matching

I'm writing a web app and trying to use mod rewrite to pretty up my URL's. I'm using the following in my htaccess file but there is a problem. If you try to go to /members it takes you to the right page but if you try to go to /members/1234 it still takes you to the members.php page not the member_profile.php page. I know this is because the request is matching the first rule but I don't know the best way to fix this. Should I just reorder them with the most restrictive first or is there a more correct way? Thanks.

RewriteEngine On
# prevent indexing directories
Options -Indexes
# members section
RewriteRule ^members /scripts/members.php
# member profile page
RewriteRule ^members/([0-9]+) /scripts/member_profile.php?id=$1
# groups section
RewriteRule ^groups /scripts/groups.php
# group profile page
RewriteRule ^groups/([0-9]+) /scripts/group_profile.php?id=$1

Upvotes: 0

Views: 873

Answers (1)

Jon Lin
Jon Lin

Reputation: 143916

You need to match against the end of the string using $ (and you also need to use the L flag to stop rewriting):

RewriteEngine On
# prevent indexing directories
Options -Indexes
# members section
RewriteRule ^members$ /scripts/members.php [L]
# member profile page
RewriteRule ^members/([0-9]+)$ /scripts/member_profile.php?id=$1 [L]
# groups section
RewriteRule ^groups$ /scripts/groups.php [L]
# group profile page
RewriteRule ^groups/([0-9]+)$ /scripts/group_profile.php?id=$1 [L]

Upvotes: 1

Related Questions