WordPress – redirect traffic to your primary domain

This is a snippet that allows you to redirect all your incoming traffic to a single primary domain.

You may end up with web sites that have multiple domains. Most commonly, site owners will want both their www and non-www domain names to end up in the same place. Later version of WordPress handle this automatically. However, web sites can change domain name for many reasons (e.g company name change, development work on a sub-domain, site restructure and so on).

It generally, and usually, best to control your traffic by configuring your web server to handle any such change. There are times though when this is not possible, or simple that you want (as a WordPress developer) the speed and control that goes with managing it from with WordPress itself.

function tcb_redirect_to_primary_domain() {
  $schema           = is_ssl() ? 'https://' : 'http://';
  $requested_domain = strtolower($schema . $_SERVER['HTTP_HOST']);

  $primary_domain = get_bloginfo('siteurl');
  if( defined('WP_SITEURL') && '' != WP_SITEURL )
    $primary_domain = WP_SITEURL;

  if( empty($primary_domain) ) return; // Something is really wrong.

  $primary_domain = strtolower($primary_domain);

  // strip subdirectories.
  if( preg_match('|^(https?://)([^/]+)/.+|', $primary_domain, $matches) )
    $primary_domain = $matches[1] . $matches[2];

  $primary_domain    = rtrim($primary_domain, '/');
  $requested_domain  = rtrim($requested_domain, '/');

  if( $primary_domain !== $requested_domain ){
    $redirect = $primary_domain . $_SERVER['REQUEST_URI'];
    wp_redirect( $redirect, 302 );
add_action('template_redirect', 'tcb_redirect_to_primary_domain');

This is pretty much a follow up to Divy Dovy’s post on WordPress domain redirection.

After Dave asked me about it, I realised that what I use at work is at times more simple, and others more complex, but was never really relevant to any other company or person. So I thought I would strip out the irrelevant bits and see what was left. and as you can see it is really not much more than Dave’s excellent snippet. He should give himself more credit!

Published by


Open Source Architect (Web Geek)

3 thoughts on “WordPress – redirect traffic to your primary domain”

Comments are closed.