How do you use a regex in a htaccess file?
I created a regex [0-9]{1,10}[-][0-9a-z]{5,9}
to find 1 to 10 numbers followed by a dash followed by 5 to 9 numbers and lowercase letters, and as far as I can tell its working.开发者_C百科 But how do I use it in a htaccess file to mask URLs from http://website.com/realpage.php?id=00000-a0a0aaa0 to http://website.com/00000-a0a0aaa0.
The rule I'm using at the moment is...
RewriteRule /[0-9]{1,10}[-][0-9a-z]{5,9}/?$ realpage.php?id=$1 [QSA,L]
...but it doesn't seem to be working.
Firstly, my guess would be you want to mask the other way round.
Anyway, your RewriteRule will be:
RewriteRule ^([0-9]{1,10}-[0-9a-z]{5,9})/?$ realpage.php?id=$1 [QSA,L]
Notes:
- Assuming your rule is in .htaccess file, you don't need to
wrap your patterns in slashes (
/
). - You don't need to include the first url slash (the one after the domain).
- The middle dash doesn't have to be in brackets as you need just one dash.
- Lastly, you need to wrap the whole thing in parentheses to be
able to reference it (rewrite) to the real path using
$1
in this case.
Hope that makes sense.
Well, you need brackets around the bit you wish to match if you are using it as a replacement, the $1
says the first matching bracket group, also you do not need the []
around the dash -
.
RewriteRule /([0-9]{1,10}-[0-9a-z]{5,9})/?$ realpage.php?id=$1 [QSA,L]
Alternatively, if you wanted it the other way, your "mask URLs from" is confusing.
You can not match against query string parameters with RewriteRule
directly.
You have to use RewriteCond
to match against it, then use a RewriteRule
to do the rewriting.
RewriteCond %{QUERY_STRING} id=([0-9]{1,10}[-][0-9a-z]{5,9})
RewriteRule ^realpage.php$ /%1/ [L]
精彩评论