Web Development

Redirect A Folder To A Subdomain

I've recently had to migrate a website which needed to switch a URL from www.example.com/blog/ to be on a sub-domain to http://blog.example.com/. When you do a site migration like this you need to make sure that you redirect all previous URLs from the sub-folder to the sub-domain. This is so you can keep the SEO value of all these previous pages, same with all the previous links you've added in social media you need to make sure people can still find your content.

To redirect all these links from a sub-folder to your new sub-domain you can add some code into your htaccess file.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]
RedirectMatch 301 ^/blog/(.*)$ http://blog.example.com/$1

Things to note in this code are the htaccess flags which are at the end of the URLs inside the square bracket. The first htaccess flag is [NC] which means nocase, so it doesn't matter what case the URL is, the htaccess will still catch it.

The other flag used is [L, R=301], the L means that this is the last command in this conditional rule, the R=301 stands for a redirection using the R flag and the number stands for the type of redirected will take place. So if a permanent redirect is needed you will use the 301 redirect [L,R=301], if you want a temporary redirect then you will use a 302 [L,R=302].

Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial