PDA

View Full Version : Mod_Rewrite Integer Rules


Sarcasmos
07-24-06, 01:34 AM
Greetings,

I did a quick look through the Mod_Rewrite links in the sticky, and didn't come up with what I need. Perhaps someone here will have the information.

I'm looking to create basically a set of "virtual directories" but the rule should apply only to integers. I.E. if a visitor types in mysite.com/15 it would be redirected to mysite.com/?id=15, but if mysite.com/abc was typed in, no redirection would take place.

Your assistance is greatly appreciated.

Have a pleasant week.

Regards,
Josh

duesi
07-24-06, 04:24 AM
You need a regular expression that matches integers:


# Turn it on
RewriteEngine on

RewriteRule ^([0-9]+)$ http://mysite.com/$1


You see that i Put the Expression [0-9]+ ([0-9] is the carachter class of integers, + indicates that there might be more than one) in (). I then reference this by $1 (this is the first mateched ()-pair, $2 would be the second asf.)

Regular Expressions have the tendency to mystify people, so make sure you look at something like this:

http://www.regular-expressions.info/

Or

http://www.regular-expressions.info/hipowls.html

Happy Coding!

Sarcasmos
07-24-06, 06:58 AM
Thanks, duesi!

Here's how I went about it:

# Turn it on
RewriteEngine on

RewriteRule ^([0-9]+)$ http://mysite.com/?id=$1 [R]

That seems to be working fine to turn mysite.com/1 into mysite.com/?id=1. I added the [R] as it seemed to be used in similar situations, but I'm a real novice at this - does it actually affect such a case?

Are there any security risks involved when using this? The numerical variable will be used to plug into the database, however, I don't see how an integer could cause any problem (the field in the table is restricted to a specific length). Obviously it will be re-checked as an integer prior to insertion (so that no one can type mysite.com/?id=abcd, etc.).

Once again, thank you very much.

Have a pleasant week.

Regards,
Josh

duesi
07-24-06, 03:00 PM
If you specify [R], apache sends code 302 (Moved Temporarily) to the browser, in other words, the browser knows it has been redirected. If you don't do this, the browser does not know it.

Security-wise I don't see any issues here.