0
votes

I have a bunch of domains I would like to be redirected (301) to domain.com, preserving Query String and with additional parameters.

It seems I got a little bit rusty with mod_rewrite as I can't find simple solution for this problem.

RewriteEngine On
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)$ http://domain.com/?utm_source=%{HTTP_HOST}&utm_medium=redirection [R=301]
RewriteRule ^(.*)$ http://domain.com/?%{QUERY_STRING}&utm_source=%{HTTP_HOST}&utm_medium=redirection [R=301]

I would like it to:

IF Query String is empty: 301 to http://domain.com/?utm_source=%{HTTP_HOST}&utm_medium=redirection, where %{HTTP_HOST} should be resolved to source domain (preserving Query String)

ELSE (IF Query String isn't empty): RewriteRule ^(.*)$ http://domain.com/?%{QUERY_STRING}&utm_source=%{HTTP_HOST}&utm_medium=redirection [R=301]

I wouldn't like to write RewriteCond for each domain I'm about to redirect as there are going to be many of such combinations.

Is there any elegant and simple way to solve this with minimum of code?

1

1 Answers

0
votes

You're pretty close. I would change it a little so there is no repetition and you're guaranteed to have a valid URL.

RewriteEngine On
# append an & to the query if it exists
RewriteCond %{QUERY_STRING} .+
RewriteCond %0& .+
RewriteRule ^ - [E=Q:%0]
# get host so it can be escaped with B flag
RewriteCond %{HTTP_HOST} .*
RewriteRule ^ http://domain.com/?%{ENV:Q}utm_source=%0&utm_medium=redirection [NE,B,L,R=301]

Read the docs on RewriteRule flags to see why I've used those.