Blog posts on one subdomain, pages on another

I might have a solution for you.

First steps:

  1. Within your domain’s DNS manager you need to create a CNAME record. The name would be blog and the hostname would be your domain name. This is necessary because the browser needs to know where to point the subdomain blog.mydomain.com to;
  2. Second, you need to tell apache (I suppose you are using apache) where is the subdomain blog.mydomain.com’s directory location. This is necessary because once the browser knows in which server to find your subdomain, then it needs apache to tell it in which folder to look at.

Once you are done with the first steps maybe you will have to wait for at least 15 minutes in order to be sure your changes were all propagated.

If you just want your single posts to be accessed via blog.mydomain.com/xxxx/xx/xx/my-post you are done. But, be warned that any page within your site will be accessed via blog.mydomain.com/some-page. For example, the user will be able to access both mydomain.com/my-contact-page and blog.mydomain.com/my-contact-page.

Besides, the changing to domain blog.mydomain.com is not being forced. If you want it to be forced you need to edit your .htaccess file and insert before the wordpress tag the following:


# BEGIN custom redirect
# You might want to change 'blog' to your current blog page slug or to sth else you want!
<IfModule mod_rewrite.c>
# Here we are making sure when the user accesses blog.mydomain.com he will see the blog page content.
RewriteCond %{HTTP_HOST} ^blog\.
RewriteCond %{REQUEST_URI} ^\/$
RewriteRule ^.*$ index.php?pagename=blog [L]

# Here we are redirecting mydomain.com/2016/12/16/my-post to blog.mydomain.com/2016/12/16/my-post
RewriteCond %{HTTP_HOST} !^blog\.
RewriteRule ^([0-9]{4})\/([0-9]{1,2})\/([0-9]{1,2})\/(.+)\/?$ http://blog.mydomain.com/$1/$2/$3/$4 [L,NC]

# Here we are redirecting mydomain.com/blog to blog.mydomain.com
RewriteRule ^blog\/?$ http://blog.mydomain.com [L,NC]
</IfModule>

# END custom redirect

Pay attention to the comments along the code snippet in order to perform your own changes in case you need to.

If you want to prevent another pages from being seen through the subdomain you can add this code snippet in your functions.php file:


function push_redirect() {

    $host = $_SERVER['HTTP_HOST'];

    // If we are not seeing the subdomain we have no reasons to continue.
    if ( !preg_match( "/^blog\./", $host ) )
        return;

    // If we are seeing blog homepage or single post we have no reasons to continue.
    if ( is_home() || is_singular( 'post' ) )
        return;

    $site_url = site_url();
    $uri = $_SERVER['REQUEST_URI'];
    $redirect_to = $site_url . $uri;

    wp_redirect( $redirect_to, 302 );

    exit;

}

add_action( 'template_redirect', 'push_redirect', 10 );

I hope this is what you were looking for.

Leave a Comment