matpop
matpop

Reputation: 2020

mod_rewrite: Demystifying RewriteBase (once and for all)

I keep seeing this (for neatness, I'm omitting IfModule and RewriteEngine directives):

RewriteBase /somedir/                  #1
RewriteRule ^index\.php$ - [L]         #2
RewriteCond %{REQUEST_FILENAME} !-f    #3
RewriteCond %{REQUEST_FILENAME} !-d    #4
RewriteRule . /somedir/index.php [L]   #5

From the documentation (and my experience):

When using the rewrite engine in .htaccess files the per-directory prefix [...] is automatically removed for the RewriteRule pattern matching and automatically added after any relative (not starting with a slash or protocol name) substitution encounters the end of a rule set. See the RewriteBase directive for more information regarding what prefix will be added back to relative substitutions.

Now, line #5 above is NOT a relative substitution (note the leading slash), so line #1 has no effect, since no prefix is added for "absolute" substitutions.
Then my question is, isn't there redundancy between directive #1 and part of #5?

Upvotes: 2

Views: 826

Answers (1)

anubhava
anubhava

Reputation: 784898

Then my question is, isn't there redundancy between directive #1 and part of #5?

No it is not a redundancy actually. It is only because you're using absolute URL here which tell mod_rewrite engine to use absolute URL in rewrite instead of relative one.

If your 5th line becomes:

RewriteRule . index.php [L]

Then RewriteBase will be in effect and will be used to rewrite the URI as: /somedir/index.php

Main advantage of using RewriteBase is that you don't need to keep repeating /somedir/ in all of your rules present in the same .htaccess file.

How to get RewriteBase dynamically:

RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]

About WP:

Wordpress could safely remove the absolute path from the RewriteRule since they are using absolute path anyway. But the thing is that so many of WP plugins overwrite that .htaccess file so they just don't want to rely on presence of RewriteBase line.

Upvotes: 2

Related Questions