Let’s say you have URL like this:
http://acme.com/my-old-url
that you want to redirect to a new url:
http://acme.com/new-url
This is easily accomplished with a rewrite rule:
1 |
RewriteRule ^my-old-url /new-url [R=201,L] |
But what if the source URL has a url parameter like:
http://acme.com/my-old-url?id=27
In this case we need to use RewriteCond to match the url parameter:
1 2 |
RewriteCond %{QUERY_STRING} ^id=27$ RewriteRule ^my-old-url /new-url? [R=301,L] |
Notice the question mark (?) at the end of “/new-url?”. This causes the query string to be discarded. If the question mark is not included then the redirect will go to:
http://acme.com/new-url?id=27
If you want to keep the query string then you can explicitly add it with the QSA option like:
1 2 |
RewriteCond %{QUERY_STRING} ^id=27$ RewriteRule ^my-old-url /new-url [R=301,L,QSA] |
Also in Apache 2.4 and latter the QSD option can be used to exclude the query string with the same effect at the trailing question mark:
1 2 |
RewriteCond %{QUERY_STRING} ^id=27$ RewriteRule ^my-old-url /new-url [R=301,L,QSD] |