Mod Rewrite Appending Query String Parameters, Not Replacing

687 Views Asked by At

I am trying to generate an external redirect that involves a few specific tasks.

  1. If specific query string value is found in the URL, redirect.
  2. If redirected, replace one of the query string parameter names but not its value.
  3. If #1 is false, then ignore rewrite and proceed

Example: I have the url http://foobar.com/?a=123&b=456&c=blah

First, if parameter c = blah, redirect to http://barfoo.com/

Second, replace a with x parameter so the final URL is http://barfoo.com/?x=123&b=456&c=blah

Below is my best guess so far after researching on http://mod-rewrite-cheatsheet.com/ and Hidden features of mod_rewrite

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.foobar\.com$ [NC]
RewriteCond %{QUERY_STRING} ^a=(.*)&b=(.*)&c=blah$ [NC]
RewriteRule ^(.*)$ http://barfoo.com/?x=%1&b=%2&c=blah [NC,L,QSA,R=301]

However, the URL is appending the query string, not replacing.

I get redirected to http://barfoo.com/?x=123&b=456&c=blah&a=123&b=456&c=blah

1

There are 1 best solutions below

0
justacoder On

smacks forehead

Removing QSA from the flags solved the issue. QSA means "append the existing query string to the current rewrite rule." It ignores whatever new query string parameters you are adding.

I thought it was needed to have query string parameters exist for the rewrite rule itself.

RewriteRule ^(.*)$ http://barfoo.com/?x=%1&b=%2&c=blah [NC,L,R=301]