1

Here are my nginx rewrite rules

rewrite ^(.*)$ http://www.destination.com/main.php?utm_source=xxx&utm_medium=yyy&utm_campaign=zzz permanent;

Everything works so far except when there's query arguments.

This is a permanent 301 redirect, and I need to configure the case when there's query string, it will be appended before the utm tracking query.

How do I do this while also taking care of rewrite without query string?

eg.

http://www.from.com/?test=ABC

goes to

http://www.destination.com/main.php?test=ABC&utm_source=xxx&utm_medium=yyy&utm_campaign=zzz

instead of

http://www.destination.com/main.php?utm_source=xxx&utm_medium=yyy&utm_campaign=zzz&test=ABC

1 Answer 1

2

You can insert the query arguments manually, but you will need to use a map to calculate whether an & separator is required.

The map should be placed in the http block:

map $is_args $separator {
    default "";
    "?"     "&";
}

The rewrite would then look something like this:

rewrite ^(.*)$ /some/url.php?$args${separator}q=$1? permanent;

See this document for details.

Sign up to request clarification or add additional context in comments.

3 Comments

Works perfect. Can you elaborate what the map block where "?" and "&" do? Is map applying certain condition here?
@KDX the $is_args variable is set to "?" if a query string is present. We need to map that to a "&" to join our argument to the existing query string ($args) unless it's empty.
Is that meant $separator will be "" if there's no query string? If there's is query string, $separator will become "&". Am I understanding correctly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.