Change the default main domain folder to subfolder

Basics of .htaccess

Crédit illustration : Unsplash

The origin of all this, you should know that I based on a new hosting service for creating this blog. So I took the opportunity to reorganize my file hierarchy. In order not to envahier the root of my storage space, I installed the blog in a subfolder named "blog". The problem that was directly posed was simple: the address to access it would have been lissot.info / blog, I wanted that the blog is accessible directly from the root of the domain name.

To do this, one solution is to use the .htaccess file.

.htaccess is a solution

Fortunately, Apache server provides a very handy mod-rewrite module named .htaccess. This file can overwrite the server setting and redirect all requests from the root of the domain to the target sub folder. So, I simply put the code below in .htaccess (in the root folder).

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?main\-domain.com$ [NC]
RewriteCond %{REQUEST_URI} !^/sub\-folder/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /sub-folder/$1
RewriteCond %{HTTP_HOST} ^(www.)?main\-domain.com$ [NC]
RewriteRule ^(/)?$ sub-folder/index.php [L]

Replace main\-domain.com with the actual main domain's name. Don't forget to use escape string \ in RewriteCond as it use regular expression to determine the match. For example if your domain spell like www.my-domain.com, you need to use it as www.my-domain.com. For more information about regular expressions (RegEx), ask Google!

How it works?

  • line 1 - ensure that server already know that we are going to use mod-rewrite
  • line 2 – if the request from http is main-domain.com or www.main-domain.com, it goes to the next line
  • line 3 – if the requested destination is not the folder /sub-folder, it goes go to the next line
  • line 4 – if the requested name is not an existing file in root directory, it goes to the next line
  • line 5 – if the requested name is not an existing directory in root directory, it goes to the next line
  • line 6 – forward request to /sub-folder/
  • line 7 – if the requested domain is main-domain.com (without any string afterward), it goes to the next line
  • line 8 – forward request to the default file under sub-folder directory (index.php for this example)

That's it. If you never experienced with .htaccess, it will be a little bit confusing. Therefore, just copy .htaccess code and replace your main-domain and sub-folder.