.htaccess mod_rewrite trick - Dynamic RewriteBase

in apache •  7 years ago 

Do you develop websites on Apache?

Do you use a secondary development or test environment (you should!)?

Do you run into the same problem as me with mod_rewrite where you have to specify a RewriteBase but that stops it working in the live environment?

Editing it each time you want to upload an update is a pain right?

Let me solve that for you!


In short...

RewriteBase /
RewriteCond $0#%{REQUEST_URI} ([^#])#(.)\1$
RewriteRule ^.*$ %2index.php [QSA,L]

Do you want that explaining? I'll try...

First off, we have to define RewriteBase as the root element.

RewriteBase /

Then we get the path from the root to the .htaccess file, that's the magic part. Are you ready?

RewriteCond $0#%{REQUEST_URI} ([^#])#(.)\1$

Now this one may take a "little" explaining.

%{REQUEST_URI} is the full request URL, I'm sure you knew that right?
$0 actually comes from the RewriteRule (in this case .* or everything FROM this directory down)

So if the .htaccess was in a subdirectory called "test" and you went to

/test/bob/steve/index.html

then the value would look like

bob/steve/index.html#test/bob/steve/index.html

The condition would match to:
%1 -> bob/steve/index.html

is the separator, not saved

%2 -> test/
/1 is %1 repeated

Or perhaps better seen as:

bob/steve/index.html CUT # CUT test/ CUT bob/steve/index.html

The key here is repeating %1 (via /1), then using that to separate it out. But how do you use it?

RewriteRule ^(.*)$ %2index.php?somevariable=$1

At least this is how I use it. It matches everything (you can add other conditions to exclude this - for example from images) and sends it to index.php with the URL string from below the .htaccess directory passed as a variable. %2 is the path from the RewriteBase to the .htaccess file

The beginnings of a multi-tier CMS or catalogue system!

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

if i understood that - i would be majorly impressed hehehehe

but..... i don't understand it. so i'm EVEN MORE impressed!!!!

i just love how you give out info to the community for people who can ACTUALLY use this!!! someday.... someday i will understand it alllllllllllll :)

Usefull and nice post👍