Learn F5 Technologies, Get Answers & Share Community Solutions Join DevCentral

Filter by:
  • Solution
  • Technology
code share

Set your Preferred Domain (www or non-www)

Problem this snippet solves:

In case you point multiple DNS records to the same Virtual Server, you could get penalized by Google for serving identical content via multiple host names. In order to prevent that, it's a good practice to set your Preferred Domain.

The Preferred Domain is the one that you would like to use to index your site's pages (sometimes this is referred to as the Canonical Domain). Links may point to your site using both the www and non-www versions of the URL (for instance, http://www.example.com and http://example.com). The Preferred Domain is the version that you want to use for your site in the search results.

Suppose your page can be reached in multiple ways:

It's a good idea to pick one of those URLs as your Preferred (canonical) Destination, and use 301 redirects to send traffic from the other URLs to your preferred URL.

A very simple solution would be adding the following iRule code with a hardcoded Preferred Destination (www.example.com) to your Virtual Server:


    if { [getfield [HTTP::host] : 1] ne "www.example.com" } {

        HTTP::respond 301 -version auto noserver Location "http://www.example.com[HTTP::uri]"
        event disable

However, if you have many Virtual Servers, creating a proprietary iRule with a hardcoded Preferred Destination for each of them might not be an option.

Suppose you have a baseline iRule, which you apply to every HTTP/S-based Virtual Server, and you want to add the code for Preferred Domain to that baseline iRule. Or, you might want to have a dedicated iRule for setting a Preferred Domain, and you just want to assign that iRule to a Virtual Server when/where needed. That means you cannot hardcode your Preferred Domain in the iRule, because it would redirect all your Virtual Servers to that one hardcoded site.

How to use this snippet:

This iRule code expects Virtual Server name to start with the name of your Preferred Domain, separated by an underscore from the rest of the Virtual Server name.

For example, if you want www.example.com to be your Preferred Domain, then this iRule code expects the Virtual Server name to be something like www.example.com_whatever_vs

Tested on Version: