views:

49

answers:

3

I would like to redirect any php page with optional parameter to a new clean url

eg, from: account.php?id=156 to newurl/account/156

I'm using the following redirectmatch

RedirectMatch ^/cmstut/([a-zA-Z0-9_]+)[\.php]?[\?]?[a-zA-Z_]?[=]?([0-9]+)?$ /cmstut/redirect/newurl/$1/$2/$3 [L]

but the result I get is it will redirect to newurl/account//?id=156

I thought it was funny when I read somewhere where htaccess and regular expression was compared to voodoo :) we'll now I understand why

+1  A: 

I don't understand where your third subexpression is.

$1: ([a-zA-Z0-9_]+)
$2: ([0-9]+)
$3: MIA

May I recommend something more like this? /cmstut/([A-Za-z0-9]+)\.php(\??id=([0-9]+))? then you may have to use $3 to access the id number. you want the entire parameter to be optional, right?

0x90
that's because I've changed it that much that i forgot to remove the $3 and everything after .php should be optional
krike
still redirects to newurl/account/?id=156
krike
I found the solution, thank you for helping
krike
+1  A: 

I never used URL redirects in .htaccess before, but if it's plain regular expressions, this should work:

RedirectMatch ^/cmstut/([a-zA-Z0-9_]+)\.php(\?[a-zA-Z_]+=([0-9]+))?$ /cmstut/redirect/newurl/$1/$3 [L]

Since you weren't very specific in what you want, I took some guesses. This will redirect foo.php?bar=123 to newurl/foo/123 and will ignore bar.


Edit: Thinking about it, rewriting your regexp for you won't help you in the long term, and no one except you is likely to know exactly what you want. I think a better course of action is pointing you to a regexp guide. Here is one, and it's specifically targeted for mod_rewrite.

imgx64
would yours work under the condition that there is no parameter? (esp. with that = sign...)
0x90
@0x90: You're right. I edited it to be optional.
imgx64
Not specific in what i wanted? I specified I wanted to redirect from one url to another showing the result I wanted and I also specified the result i got which is not what I wanted. anyway I still have the problem, it redirects to newurl/account/?id=156 (i'm working on my localhost)
krike
I found the solution, thank you for helping
krike
A: 

I finally found the solution. I did some more research and I used a different approach which I believe was even better then what i was using

RewriteCond %{QUERY_STRING} ^id=([0-9]+)$ [NC]
RewriteRule ^([A-Za-z0-9]+)\.php$ /cmstut/redirect/newurl/account/%1? [R=302,L] 
krike