Last updated on September 21st, 2021 at 10:43 am
Sometimes, you may need to move a specific subfolder/subdirectory on your website to a separate subdomain. In such cases, you will need to redirect subdirectory to subdomain. Here’s how to redirect subfolder to subdomain using .htaccess file in Apache web server.
How To Redirect Subfolder To Subdomain
Here’s how to redirect subfolder to subdomain using .htaccess file. Please make sure you have enabled mod_rewrite in Apache web server before you follow these steps. Otherwise, Apache won’t apply the .htaccess configuration. If you have not enabled .htaccess for your website, you can add the following config lines to the Apache server config file, httpd.conf. Nevertheless, after you redirect subfolder to subdomain, you may want to use a reporting software to monitor the key metrics about your website/application such as signups, traffic, sales, revenue, etc. using dashboards & charts, to ensure everything is working well.
1. Open .htaccess file
You will typically find .htaccess file in your site’s root folder (e.g /var/www/html/). You can open it using vi editor
$ sudo vim /var/www/html/.htaccess
2. Redirect Subfolder to Subdomain
Let’s say you want to redirect example.com/blog directory to blog.example.com subdomain. There are multiple ways to accomplish this in Apache. We will look at each of them. You can use any of them as per your requirement.
Using RewriteRule
Add the following lines to your .htaccess file.
RewriteEngine on RewriteBase / RewriteRule ^/blog/(.*)$ http://blog.example.com/$1 [R=301,L]
The above lines will redirect all requests sent to /blog, to the blog.example.com subdomain. Similarly, you can redirect HTTP to HTTPS using .htaccess file.
Using Redirect
You can also do the same thing with just one line, using Redirect directive.
Redirect /blog http://blog.example.com
Using RewriteCond
RewriteEngine on RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ RewriteRule ^/?blog/(.*)$ http://blog.example.com/$1 [R=301]
The above rules work for both www.example.com as just example.com. Similarly, you can redirect to subfolder in Apache.
3. Restart Apache Server
Restart Apache Server to apply changes
$ sudo service apache2 restart
That’s it! Now your website will automatically redirect subdirectory to subdomain, that is, all requests that are sent to /blog subfolder, to blog.example.com subdomain.
By the way, if you want to create dashboards & charts to monitor your business or website, you can try Ubiq. We offer a 14-day free trial.
Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.