Mohammad
Mohammad

Reputation: 7418

optimizing Pretty URLs in .htaccess

This is the code I use,

<IfModule mod_rewrite.c>
 RewriteCond %{SCRIPT_FILENAME} !-d
 RewriteCond %{SCRIPT_FILENAME} !-f
 RewriteRule ^([^/]+)/?([^/]+) index.php?user=$1&do=$2 [L]
</IfModule>

if i give it abcd/1234 it will capture abcd first then 1234 as the second variable. But if the url was abcd/ or abcd the first capture stays the same, yet the second capture becomes d. This would cause no problem in the php code itself, yet it would be more efficient if it was not captured in the first place.

oh to clarify, neither the first or second capture are required for the index.php page. But will change its purpose if they exist.

any help with the regex code would be appreciated, and if there are anyways to improve it more or write it more efficiently i would be very grateful to know!

Thank You very Much : )
i use this tool http://gskinner.com/RegExr/ to check this.

Upvotes: 0

Views: 396

Answers (3)

AndiDog
AndiDog

Reputation: 70198

The second part ($2) is non-optional because you wrote [^/]+. I would replace the whole thing by ^([^/]+)(?:/([^/]+))? which leads to the following results:

abcd -> $1='abcd' $2=''

abcd/ -> $1='abcd' $2=''

abcd/something -> $1='abcd' $2='something'

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799062

The question mark in the rule along with the second plus sign is causing it to be split this way. You should remove the question mark since you already require at least one character in the second group.

Edit: In that case, use this:

RewriteRule ^([^/]+)(/([^/]+))?$ index.php?user=$1&do=$3 [L]

Upvotes: 0

KiNgMaR
KiNgMaR

Reputation: 1567

Very simple modification:

 ^([^/]+)/?([^/]*)

Upvotes: 0

Related Questions