Is it possible to use .htaccess to send six digit number URLs to a script but handle all other invalid URLs as 404s?

StackOverflow https://stackoverflow.com/questions/73123

  •  09-06-2019
  •  | 
  •  

Question

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.

Was it helpful?

Solution

<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/

OTHER TIPS

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!

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top