Google Analytics uses parameters in the URL query string to track referrer details such as the campaign source, medium, and keyword; however, these URLs can get quite long, and in some situations you need to make them shorter. This article discusses why you might want a shorter URL, then presents two approaches to doing it; one using the bit.ly API, and another using Apache Rewrite Rules.
Reasons to Shorten URL Parameters
As you are probably aware, the URLs used to track campaigns in Analytics can get quite long: For instance, here’s one I’m using on my LinkedIn company page (
Even without any campaign or keyword parameters it’s still quite long, and could be reduced for one of the following reasons:
- It looks messy in situations where you don’t have control over how the link is formatted: For example, I’m using this link on LinkedIn where it’s wrapped across two lines and cut off at the end. This looks ugly when an profile URL would usually just contain the domain name; I really want a clean URL to put onto my profile.
- A link like this isn’t suitable for Twitter: It’s a quite short example, but already 85 characters long.
- You might need to pass links to other people, and they could mess up the parameters.
Using the bit.ly API To Reduce the URL Size
One simple way to shorten a URL is using a service such as bit.ly: You can either construct the URL and enter it into the normal shortening form, or you can use their API to create your own URL builder that combines parameter construction and shortening into one tool. Here’s an example PHP function that will take the parameters and call the API to generate the condensed URL:
Most of this function deals with creating the URL from your campaign settings. The final part generates a request to the API, and parses the response to extract the short URL. To use it you need to enter an API username and token into the constants at the top. You can sign up here, then, once you’ve signed up, your key is located here. This is an example of using the function:
Expanding a Shortened URL Using Apache Rewrite Rules
The bit.ly approach works in many cases, but sometimes you still want to keep the domain name in the URL. For example, in my LinkedIn case above, I want
www.ppcbullet.com to appear in the profile, but not in the long query string.
This can be done by putting something into the URL that can be picked up on the server and used to redirect to the full URL with the appropriate campaign tracking parameters. One way of doing this is to use Apache mod_rewrite; one rule for each shortened URL. The following rewrite rule will redirect my profile URL:
This rule redirects the URL
http://www.ppcbullet.com/?utm_source=linkedin&utm_medium=organic&utm_content=page. It’s not perfect, but a lot better than the original. If you have many URLs you want to do this with or you don’t want to use
mod_rewrite, then you could do a similar thing with a script that pulls the URL mapping out of a database.