Htaccess redirect - is this a good way?

I have the following line in my htaccess file.

RewriteRule ^/?([a-zA-Z0-9_]+)[\\.php]+$$1 [R=301,L]

Would you accept such a line or should i change it somehow?

My framework will automatically redirect none existing files to /



RewriteRule ^/?([a-zA-Z0-9_]+)[[COLOR="Red"]\\[/COLOR].ph[COLOR="Red"]p[/COLOR]]+$$1 [R=301,L]

That’s fine with the exception of the red bits in the code. However, as ScallioXTX points out, [.php]+ is trying to match, IN ANY ORDER, dot characters, p’s, h’s and p’s AGAIN!


Ah, but it will! (1) You NEVER escape the dot character in a range definition as it’s NOT a metacharacter there, it IS a dot character. The problem, as discussed above, is that the enclosed characters can appear in any order and as often as they like (one or more) with the + metacharacter modifying the range definition.

Eh, I’m not fond of wildcards like that (they’re even more difficult for newbies to learn how to use properly - as you’ll see next) and the \w is only for word characters so it won’t match the _'s t3 was after. :wink:




Don’t worry about it, you’re catching on VERY fast! Pretty soon, I can retire! :smiley:



It won’t work, because you haven’t escaped the dot. Also, [.php] does not really make sense, since it defining a regex class, and does not say php has to in that order p - h - p.
Instead you should use:

RewriteRule ^/?([a-zA-Z0-9_]+)\\.php$$1 [R=301,L] 

Note that if you’re running apache 2.x you can change it to:

RewriteRule ^(\\w+)\\.php$$1 [R=301,L] 

i.e., replace ^/? with ^ and [a-zA-Z0-9_]+ with \w+

This doesn’t work in Apache 1.x !

And I keep on learning. I love SitePoint :smiley:

Ah your right i forgot the escape :slight_smile:

And again your right, why did i not see that one…

Thank you for your input, much appreciated!