Rich Bradshaw
Rich Bradshaw

Reputation: 72975

Why doesn't this mod_rewrite 301 redirect work?

Other RewriteRules work, so I've replaced those, and put this one first. Mangling it deliberately returns a 500 error, so I'm confident that my syntax is wrong, rather than my configuration.

I have redesigned a site that used to have URLs like:

/product_view.asp?product_id=123&images_id=456

My new site has URLs like:

/shop/product/123

(where the two 123s are the same as I've kept the same database)

My RewriteRule is:

RewriteRule ^product_view.asp\?product_id=([0-9]+).*$ /shop/product/$1 [R=301,L]

but nothing happens – no errors, no 500s, just nothing.

What have I done wrong?

Upvotes: 0

Views: 81

Answers (1)

yasu
yasu

Reputation: 1364

RewriteRule refers only path, that does not include QUERY_STRING. Find product_id from QUERY_STRING with RewriteCond.

RewriteCond %{QUERY_STRING} (?:^|&)product_id=([0-9]+)
RewriteRule ^product_view\.asp$ /shop/product/%1? [R=301,L]

Grouped part in RewriteCond can be referred as %1. It can be used in RewriteRule.

If ? is placed at the end of substitution part of RewriteRule, QUERY_STRING will be discarded. (You can use QSD flag instead if your Apache version is 2.4 or later.) It is not always needed, but perhaps you don't like such ugly URL as /shop/product/123?product_id=123&images_id=456.

Check mod_rewrite document for detail.

Upvotes: 2

Related Questions