How to Redirect Subdomain to Subfolder using .htaccess


redirect subdomain to subfolder using htaccess

When you restructure your website, you might end up moving an entire sub domain to a sub folder. In this case, it’s essential to redirect subdomain to subfolder so that search engines and site visitors know that your web pages have moved. Let us look at how to redirect subdomain to subfolder using .htaccess

 

 

How to Redirect Subdomain to Subfolder using .htaccess

Here are the steps to redirect subdomain to subfolder using .htaccess. Basically, you need to open .htaccess using a text editor, copy-paste the commands given below and restart your Apache server to apply the changes.

However, before we proceed, please ensure that you have enabled mod_rewrite & .htaccess on your Apache server. If you haven’t, then here’s how you can enable .htaccess in:

  1. Ubuntu/Debian systems
  2. CentOS and similar systems

 

.htaccess file allows you to setup redirect rules without accessing Apache config files. You will find it in your website’s root folder (e.g /var/www/html in Linux). If you can’t find it, you can create it. Just name it .htaccess. Nothing before or after.

 

Open .htaccess file


$sudo nano /var/www/html/.htaccess

 

Add URL Rewrite Rules

Let us say you want to redirect blog.example.com to example.com/blog. Paste the following code in .htaccess. Replace example.com with your own domain. Replace blog with your sub domain and folder names


RewriteEngine On

RewriteCond %{HTTP_HOST} ^blog\.example\.com$
RewriteCond %{REQUEST_URI} !^/blog/
RewriteRule (.*) /blog/$1

 

Restart Apache Server

Restart Apache Web Server to apply changes


$ sudo systemctl restart apache2 [Ubuntu/Debian]
$ sudo systemctl restart httpd [RHEL/CentOS]

 

Congratulations! Apache will automatically redirect subdomain to subfolder using .htaccess.

To redirect more sub domains to subfolders, add similar blocks of rules to .htaccess for each subdomain.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!