WordPress Function to Redirect All Incoming Domain Requests to the Primary Domain Variant

This is something that has bugged me for ages. Surely there’s a way to redirect domain.com, *.domain.com, www.domain-variant.com, etc to the primary WordPress domain, www.domain.com using a WordPress function? Something that I can simply copy and paste for all my theme development without having to worry about the eventual web hosting environment or domain host.

We’re assuming here that we need to do this within WordPress because:

  • The domain host doesn’t provide enough web forwarding control
  • We’re on shared hosting where we can’t do an .htaccess redirect
  • We want to do it within WordPress for any other reason

I’m also assuming that all the domains and variants are already pointing at the correct server/virtual host.

I put a shout out to the http://www.wp-brighton.org.uk/ WordUp! mailing list to see what approaches people take. My favourite answer was from Tom Barrett, who suggested:

add_action('setup_theme', 'check_my_host');
function check_my_host(){
// Check host in _SERVER
// Find site_url
// Check protocol http/https
// String together pieces to compare with host
// Parse PATH_INFO (to deal with installs in sub directories)
// Use wp_redirect() and exit.

Now, I’m not as clever as Tom, so my code isn’t as thorough as his, but as I don’t tend to do sites that use SSL anyway, I decided to keep things simple and ignore that!

Here’s my variant, totally inspired by Tom:

// Redirect all site requests to this virtual host to the siteurl address
function check_my_host() {
// Check host in $_SERVER
$incomingHost = 'http://' . $_SERVER['HTTP_HOST'];
$incomingQuery = $_SERVER['REQUEST_URI'];
// Find site_url
$primaryHost = get_bloginfo ( 'siteurl' );
$redirectTarget = $primaryHost . $incomingQuery;
// Compare incoming and primary hosts
if ( strtolower( $incomingHost !== $primaryHost ) ) {
// If they're not equal, use wp_redirect() and exit
wp_redirect( $redirectTarget, 301 ); exit;
add_action('template_redirect', 'check_my_host');

I’ve tested it and it seems to work solidly for redirecting both domain root and domain + query requests.

I’ve got no doubt this can be improved (to account for http/https protocols and various other clever checks) so please do leave comments and I’ll update this function (with credits where appropriate).

One comment

Comments are closed.