Apache Redirect Root URL to Subfolder
Category : How-to
The Apache HTTP is able to redirect traffic to a specific URL with use of the Apache mod_rewrite. mod_rewrite can do at least 100 other things and I’ll include some of those in a later blog post.
Let’s take a look at a simple redirection of traffic from / to /mysubfolder.
For example, this would redirect all traffic sent to http://www.jamescoyle.net/ to http://www.jamescoyle.net/mysubfolder/
This can be very helpful when you are using a reverse proxy and the application you are proxying is on a sub folder in the URL path. You can simply use this technique to redirect all users to the subdirectory folder path.
Make sure the module is enabled. In Ubuntu you can simply run the a2enmod command however in RHEL/ Cent OS you may need to add the module manually to your httpd.conf file.
a2enmod rewrite
Then in your sites file you will need to add the following code.
RewriteEngine on RewriteCond %{REQUEST_URI} ^/$ RewriteRule (.*) /mysubfolder/ [R=301]
- RewriteEngine on is used to specify to Apache that this site will use Rewrite rules to transform the URL
- RewriteCond is the match part of the pattern. If the URL matches this pattern then RewriteRule will be applied. This particular pattern is checking if the requested URL path is equal to /.
- RewriteRule is going to add /mysubfolder/ to the URL which only contains the domain due to the above RewriteCond already performing the check.