RewriteBase Explained

When to use & how?

RewriteBase is used to fix cases where mod_rewrite is running in a .htaccess file not at the root of a site and it guesses the wrong web path (as opposed to filesystem path) for the folder it is running in. So if you have a RewriteRule in a .htaccess in a folder that maps to http://example.com/myfolder you can use:

RewriteBase myfolder

How does it work?

Consider the following directive:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog

RewriteRule ^blog/rewritebase-explained$ post100.html
</IfModule>

Now if you were to access the url example.com/blog/rewritebase-explained, Apache would perform the following steps:

  • Strip the domain, and leading slash and pass the following path to the rewrite rules:blog/rewritebase-explained
  • Apply the rewrite rules
  • In the example, the single rule matches, and the path becomes post100.html
  • Apply the RewriteBase rule to the path to create a path of: /blog/post100.html
  • Apache adds in the forward slash between blog and post100.html
  • Alternatively, you could write RewriteBase /blog as RewriteBase /blog/ which would accomplish the same thing.
  • Apache then looks for the content at /blog/post100.html on the file system.
  • Assuming the content is found the url example.com/blog/rewritebase-explained serves up the physical file from /blog/post100.html

4 thoughts on “RewriteBase Explained

Leave a comment