Remove Google Analytics utm Query String with nginx

Using Google Analytics to gain traffic insights for your WordPress or WooCommerce site can track visitors and conversion rates. If you use tracking for email blasts when you publish new posts or product deals, you may find visitors get a slower experience. Google Analytics adds a query string that looks something like ?utm_source=mailchimp which bypasses any caching you may have enabled. Google uses this query string for tracking, however, Google tracks using client side javascript which means we can remove this Google Analytics query string, deliver faster pages to clients and still track using Google Analytics. This will fix your website being slow when you send out email campaigns with Analytics tracking enabled since your cache will actually be used instead.

This guide is for removing Google Analytics query strings with nginx, the Apache .htaccess version is here. The Varnish version will be published in the future.

If you use Google Adwords then see the guide about removing the gclid query string too.

Speed Tests with and without Google utm Query String

Using pingdom, the front page of this site loads in 339 ms without the query string

When repeating the speed test adding the ?utm=source=mailchimp query string loads in 1.01 seconds because the cache is bypassed.

Read on to learn how to remove the Google Analytics tracking query string using nginx rewrites for WordPress.

Remove Google Analytics utm Query String for nginx

In your nginx virtual host file, usually in /etc/nginx/sites-available or /etc/nginx/vhosts and add this snippet

#remove utm query string
if ($args ~* "utm") {
    #? in uri? drops the utm query string
    rewrite ^(.*)$ $uri? permanent;
}

Save the virtual host and then verify the nginx configuration syntax is OK.

sudo nginx -t

Reload the nginx service if there were no syntax errors.

sudo service nginx reload

Now when you test a URL with the ?utm_source query string you will see it is removed.

Sources

Is Google Analytics executed server side or client side?
nginx Strip Query String Rewrite
Remove Parameters with nginx rewrites
nginx http rewrite module