Sunday, May 27, 2012

How does RewriteBase work in .htaccess


I have seen this in a few .htaccess examples




RewriteBase /



It appears to be somewhat similar in functionality to the <base href=""> of HTML.



I believe it may automatically prepend its value to the beginning of RewriteRule statements (possibly ones without a leading slash)?



I could not get it to work properly. I think it's use could come in very handy for site portability, as I often have a development server which is different to a production one. My current method leaves me deleting portions out of my RewriteRule statements.



Can anyone explain to me briefly how to implement it?



Thanks


Source: Tips4all

4 comments:

  1. RewriteBase is only useful in situations where you can only put a .htaccess at the root of your site. Otherwise, you may be better off placing your different .htaccess files in different directories of your site and completely omitting the RewriteBase directive.

    Lately, for complex sites, I've been taking them out, because it makes deploying files from testing to live just one more step complicated.

    ReplyDelete
  2. In my own words, after reading the docs and experimenting...

    You can use RewriteBase to provide a base for your rewrites. Consider this...

    # invoke rewrite engine
    RewriteEngine On
    RewriteBase /~new/

    # add trailing slash if missing
    rewriteRule ^(([a-z0-9\-]+/)*[a-z0-9\-]+)$ $1/ [NC,R=301,L]


    This is a real rule I use to ensure that URLs have a trailing slash. IMO, it looks neater. This will convert http://www.example.com/~new/page to http://www.example.com/~new/page/. By having the RewriteBase there, you make the relative path come off the RewriteBase parameter.

    ReplyDelete
  3. AFAIK, RewriteBase is only 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


    If mod_rewrite isn't working correctly.

    Trying to use it to achieve something unusual, rather than to fix this problem sounds like a recipe to getting very confused.

    ReplyDelete
  4. This command can explicitly set the base URL for your rewrites. If you wish to start in the root of your domain, you would include the following line before your RewriteRule:

    RewriteBase /

    ReplyDelete