Last Updated on April 20, 2021 by Amit

How RewriteBase works in htaccess

RewriteBase directive sets a base path for all relative links in RewriteRules.
In this article I will tell you how RewriteBase works and when we should and when we shouldn’t use it in our htaccess file.

How RewriteBase works in htaccess

This directive appends a custom path to all relative rewrite substitution strings in an htaccess file.
RewriteBase is part of Apache mod-rewrite a module provided by Apache for rewriting URLs.

It works with mod-rewrite directives such as RewriteRule.
Let’s see some real world htaccess rules to better understand how it actually works .
The following rule in a /subfolder/. htaccess does not contain a RewriteBase and the substitution string is using a relative path starting without /

RewriteEngine on
RewriteRule ^foobar$ file.php [R]

We created the above rule to redirect /subfolder/foobar to /subfolder/file.php but unfortunately this will redirect you to the file.php located inside root folder.
This is because “file.php” in the rule’s substitution string is pointing to root directory .
It’s looking for the file in your root directory so your redirected URL path will look something like “/file.php” instead of “/subfolder/file.php” .
You can fix this either by using a RewriteBase or using absolute file path in your rule’s target.

RewriteEngine on
RewriteBase /subfolder/
RewriteRule ^foobar$ file.php [R]

The rule above will now correctly point your URL to “/subfolder/file.php” .
The “/subfolder/” perfix is automatically copied from the RewriteBase to the relative target path in the rule above.
You don’t need to use RewriteBase if you are using an absolute path pointing to the current directory. The following is an example of that :

RewriteEngine on
RewriteRule ^foobar$ /subfolder/file.php [R]

Since the rewrite destination in the rule above is using an absolute path pointing to the subfolder , this will redirect your URL to the correct location. You don’t need to use RewriteBase here as the base path isn’t copied to absolute substitute strings.

If you are new to htaccess , and want to learn some basics of mod-rewrite ,You can check out this mod-rewrite tutorial for beginners .

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.