I am trying to redirect from an url to another url but keeping the queries. For example, from
/oldurl?query1=yes&query2=yes&... (or any list of queries)
to
/newurl?fixedquery=yes&query1=yes&query2=yes&...
So in pratice it would redirect the old url and its queries to a new url, keeping the old queries, plus a fixed query.
This is what I have been trying to use (unsuccessfully) in the .htaccess:
RedirectMatch 301 /oldurl/?$ newurl/?fixedquery=yes&$1
I also tried before using Rewrite
RewriteCond %{QUERY_STRING} ^fixedquery=yes$
RewriteRule ^oldurl/?$ newurl/? [R=301,L]
But this simply redirects if for /oldurl
(adding fixedquery
) and gives a 404 in case I pass a query to oldurl (e.g. /oldurl?var1=1
).
Where am I wrong?
CodePudding user response:
You need to use mod_rewrite in order to manipulate the query string. Try the following instead:
RewriteRule ^oldurl/?$ /newurl?fixedquery=yes [QSA,R=301,L]
Your example URL omits the trailing slash on the target URL, so I omitted it here. However, in your directives, you are including it?
The QSA
flag appends/merges the original query string from the request. So the resulting URL is /newurl?fixedquery=yes&query1=yes&query2=yes&...
, where query1=yes&query2=yes&...
were passed on the initial request.
UPDATE: Note that this rule needs to go near the top of the file, before any existing rewrites. The order of directives in the .htaccess
file can be important. Test first with 302 (temporary) redirects to avoid potential caching issues. And you will need to ensure the browser cache is cleared before testing.
A look at your attempts...
RedirectMatch 301 /oldurl/?$ newurl/?fixedquery=yes&$1
The RedirectMatch
(mod_alias) directive matches against the URL-path only, but you have no capturing subgroup in the regex, so the $1
backreference is always empty.
RewriteCond %{QUERY_STRING} ^fixedquery=yes$ RewriteRule ^oldurl/?$ newurl/? [R=301,L]
This matches a request for /oldurl?fixedquery=yes
and redirects to newurl/
- removing the query string entirely. However, this is also reliant on RewriteBase
being set, otherwise this will result in a malformed redirect, exposing your directory structure.