Apache Redirect Root URL to Subfolder

Apache Redirect Root URL to Subfolder

Get Social!

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.


4 Comments

Federico Granata

30-Jul-2014 at 10:07 am

I wonder how can I do the opposite.
I want to redirect every folder and subfolder and so on to the root.

Is it possible ?

    anonymous

    17-Feb-2022 at 9:38 pm

    Yes you can
    “`
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} ^/.+$
    RewriteRule (.*) /
    “`
    this checks that the file does not exist (so you can have /about.html, /contactform.php, etc, otherwise you can comment out the second line), then checks if the requested URI has *ONE* to many characters (in contrast to .* which checks for *any* to many) and this is done to prevent redirect loops, then it rewrites everything to the root.

Faruk

5-Dec-2017 at 12:54 pm

Thank you a bunch. I’ve tried so many methods and none of them seemed to work until I came through your articles. Very appreciate.

Netudd Gi

5-Dec-2019 at 9:48 am

This is not redirect, but rewrite and they are not the same.
A “redirect” sends the browser either HTTP 301 or 302 and a new Location, and the client is aware of the change of location, as the address bar in the browser changes.
Rewrite happens in the background and the client is not aware of the URL change.

Leave a Reply

Visit our advertisers

Quick Poll

Are you using Docker.io?

Visit our advertisers