views:

321

answers:

3

Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404?

For example:

http://mywebsite.com/132483

would be sent to:

http://mywebsite.com/scriptname.php?no=132483

but

http://mywebsite.com/132483a or
http://mywebsite.com/asdf

would be handled as a 404 error.

I presently have this working via a custom PHP 404 script but it's kind of kludgy. Seems to me that .htaccess might be a more elegant solution, but I haven't been able to figure out if it's even possible.

A: 

Yes it's possible with mod_rewrite. There are tons of good mod_rewrite tutorials online a quick Google search should turn up your answer in no time.

Basically what you're going to want to do is ensure that the regular expression you use is just looking for digits and no other characters and to ensure the length is 6. Then you'll redirect to scriptname.?no= with the number you captured.

Hope this helps!

Frank Wiles
+10  A: 

In your htaccess file, put the following

RewriteEngine On
RewriteRule ^([0-9]{6})$ /scriptname.php?no=$1 [L]

The first line turns the mod_rewrite engine on. The () brackets put the contents into $1 - successive () would populate $2, $3... and so on. The [0-9]{6} says look for a string precisely 6 characters long containing only characters 0-9.

The [L] at the end makes this the last rule - if it applies, rule processing will stop.

Oh, the ^ and $ mark the start and end of the incoming uri.

Hope that helps!

adam
Doh. You beat me to it by a few seconds. :)
Jeremy Privett
The R=301 is optional. It should only be used if you don't want the numeric version visible in the URL (or to spiders).
Sean Carpenter
yeah - i think 301 is the default anyway
adam
A: 
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^([0-9]{6})$ scriptname.php?no=$1 [L]
</IfModule>

To preserve the clean URL

http://mywebsite.com/132483

while serving scriptname.php use only [L]. Using [R=301] will redirect you to your scriptname.php?no=xxx

You may find this useful http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/pdf/

daniels
Thank you so much for your help! That works perfectly.
Jason Hackwith