make subdirectory root

.htaccess Make Subfolder Root

Sometimes you may need to make a subdirectory or subfolder as root, when you migrate a website. In this article, we will look at how to redirect subfolder to root using .htaccess.


.htaccess Make Subfolder Root

Here are the steps to redirect subfolder to root using .htaccess. We will look at different use cases to redirect subfolder to root. Before proceeding, please enable mod_rewrite in your Apache server. Here are the steps to do it. In all the following steps, replace sample with your subdirectory name and example.com with your domain name.


Redirect from Subfolder to Root

Let us say you want to redirect subfolder /sample/test-url to root http://www.example.com/test-url. In this case, add the following lines to your .htaccess file.

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

Also read : How to Make Directory Inaccessible in Apache


Redirect from subdomain’s subfolder to root

Let us say you want to redirect from subdomain’s subfolder blog.example.com/sample/test-url to root site www.example.com/test-url then add the following lines to .htaccess file.

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

Also read : How to Remove index.php using .htaccess


Redirect only subdirectory to root

If you want to redirect only the subdirectory /sample to root www.example.com, then add the following lines to .htaccess file.

RedirectMatch 301 ^/sample/$ http://www.example.com/

If you want to redirect to the non-www version of your website, then add the following lines to .htaccess file.

RedirectMatch 301 ^/sample/$ http://example.com/

Also read : Apache Config File Location


Redirect All URLs in folder to Specific URL

If you want to redirect all URLs in /sample subfolder to a specific URL /test-page then add the following lines to .htaccess file.

RedirectMatch 301 ^/sample/.*$ http://www.example.com/test-page

That’s it. Now when you open browser and visit a folder or a URL containing folder, it will automatically redirect to root.


After any of the above steps, you need to restart Apache server to apply changes.

$ sudo service apache2 restart

Leave a Reply

Your email address will not be published. Required fields are marked *