htaccess codes to redirect domains to directories

The codes below deals with managing domains and directories through htaccess. These codes are to be added in the htaccess files present in the root directory for the domain. If you’re new to the term htaccess, you can read more about it in the post Introduction to .htaccess file.

Redirect a directory or a page to a different link
Below code is the simplest of them all. Basically, what it does is redirect everyone who accesses your-domain.name/folder to your-domain.name/another-folder.

#redirect a directory to domain
redirect /folder http://example.com/another-folder

There is no limitation that the redirected link should be your domain. For example, if you would like to redirect everyone who tries to access your_domain.name/google to google.com, then you can use this code as shown below:

#redirect a directory to domain
redirect /google http://google.com

Display contents from a sub-folder, without changing the URL.
This code is generally used on primary domains when you want to display contents from a folder, but keep the url as your_domain.name instead of yur_domain.name/folder

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/subdirectory/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /subdirectory/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ subdirectory/index.php [L]

You will need to replace all instances of example.com with your_domain.name and all instances of subdirectory with your folder name. For exmaple, if you have a wordpress installation within a folder such as http://your_domain.name/blog , that you would like to display using http://your_domain.name Then you would use the following code:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?your_domain.name$
RewriteCond %{REQUEST_URI} !^/blog/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /blog/$1
RewriteCond %{HTTP_HOST} ^(www.)?your_domain.name$
RewriteRule ^(/)?$ blog/index.php [L]

Please leave the spaces in the code as it is. Also, if you have HTML files inside the folder, then change index.php to index.html. If you need further assistance or if you have issues using the above code, please leave a comment below.

/

Report (Please include link to post while reporting)

Leave a Reply

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