How to Use .htaccess to Redirect Domain To Subfolder


htaccess redirect to subfolder

When you change your website structure, or move some of your pages to a different location, you’ll need to redirect your old pages to a subfolder or subdirectory. Here are some of the common use cases to redirect domain to subfolder

 

How to Use .htaccess to redirect domain to subfolder

In the examples below, replace the parts in bold with your actual values.

 

Redirect all URLs in a domain to a subfolder

If you want to redirect all requests to a website (example.com), to its subfolder (e.g /blog)


RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} !^/blog/

# Rewrites all URLS [Replace "example" with the actual domain, without the TLD (.com, .net, .biz, etc)]
RewriteCond %{HTTP_HOST} ^(www\.)?example\.

# Rewrite all those to insert /folder
RewriteRule ^(.*)$ /blog/$1 [L]

 

Redirect ONLY root URL to subfolder

If you only want to redirect the root URL to subfolder and allow subfolder URLs to be accessed separately


RewriteEngine on
RewriteCond %{HTTP_HOST} example\.com [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ /blog/$1 [L]

 

Redirect subdirectory to another subdirectory in same domain

If you want to redirect all URLs in a subdirectory (e.g /blog) to another (e.g /articles


RewriteRule ^blog/(.*)$ /articles/$1 [R=301,NC,L]

 

Redirect subdirectory to another subdirectory in different domain

If you want to redirect all URLs in a subdirectory (e.g /blog) to another (e.g /articles) in a different domain (e.g anotherdomain.com)


Redirect 301 /blog http://www.anotherdomain.com/subdirectory

 

Force subfolder to go over HTTPS

If you want to serve only a specific subfolder over HTTPS, create a .htaccess file in that folder and paste the following commands


RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} somefolder
RewriteRule ^(.*)$ https://www.domain.com/somefolder/$1 [R,L]

 

If you want to force the entire website over HTTPS


RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

 

 

 

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!