user4859793
user4859793

Reputation: 45

Htaccess Rules not working on my site

I copied this code from other answer on stackoverflow, I want to shorten a long url :

for example

http://example.com/mobile/user.php?uname=foo

to

http://example.com/foo

here is my current code :

Rewriteengine on 
RewriteCond %{THE_REQUEST} ^.*/mobile/user.php\?uname=(.*).*$ 
RewriteRule . /mobile/%1 [R,L] 
RewriteRule ^(.+)$ /mobile/user.php?uname=$1 [R,L]

It is showing a wired url in browser

 http://example.com/mobile/fooHTTP 1.1 

Does anyone know why this is happening?

Upvotes: 1

Views: 27

Answers (2)

Amit Verma
Amit Verma

Reputation: 41249

Try this

 Rewriteengine on 
 RewriteCond %{THE_REQUEST} ^.*/mobile/user.php\?uname=(.*?).*$ 
 RewriteRule . /mobile/%1 [R,L] 
 RewriteRule ^(.+?)$ /mobile/user.php?uname=$1 [R,L]

This is happening because Star(*) is greedy in Regex so it consumes as much as possible. And this behaviour can be changed simply by putting a ? after the star.

(.*?)

Upvotes: 0

anubhava
anubhava

Reputation: 786359

Your regex is wrong in first rule:

RewriteEngine on

RewriteCond %{THE_REQUEST} /mobile/user\.php\?uname=([^\s&]+) [NC]
RewriteRule . /mobile/%1? [R,L]

RewriteRule ^(.+)$ /mobile/user.php?uname=$1 [R,L]

Upvotes: 1

Related Questions