htaccess redirect based on get value

I want to redirect some pages based on a value retrieved in the url.

It is necessary for me do it with htaccess.

For example:

http://www.example.com/products.php?id=1040

http://www.example.com/products.php?id=1041

http://www.example.com/products.php?id=1042

If the id value is greater than 1039 and less than 1501, apache must redirect to another page:

http://www.example.com/otherpage.html

Upvotes: 0

Views: 480

Answers (3)

Puppet Master 3010
Puppet Master 3010

Reputation: 261

You should add something like this

AddDefaultCharset UTF-8
Options +MultiViews
RewriteEngine On
RewriteRule condition/ http://www.example.com/otherpage.html [P]

However I am not sure how easy it would be to get redirect over param values.

Upvotes: 0

Jon Lin
Jon Lin

Reputation: 143886

Try:

RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteCond %1 >1039
RewriteCond %1 <1501
RewriteRule ^/?products\.php? /otherpage.html? [L,R=301] 

The first condition groups the numeric ID making it available as a backreference via %1. The next two conditions checks that this numeric ID is greater than 1039, and less than 1501. If all 3 conditions are met, the request for /products.php is redirected to /otherpage.html. The ? at the end ensures that the query string is not appended to the end.

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71384

With this sort of specific requirement, I would think performing the redirect at the application level rather than in Apache would be most appropriate. Just compare the value fo $_GET['id'] and redirect via header() as appropriate.

Either that or you have to write a relatively complex regex to search for values between 1040 and 1500 within a RewriteCond as a regular RewriteRule doesn't operate against query strings.

Upvotes: 0

Related Questions