4th Street Bar Hive-Bar

Hive-Bar Powered by Hive beta-fdb5b5b

Community post

.htaccess mod_rewrite trick - Dynamic RewriteBase

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#%REQUESTURI([#]*)#(.*)\10#%{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#%REQUESTURI([#]*)#(.*)\10#%{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=%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!

7 upvotes $0.31

Replies (2)

Review before signing

Posting as . Signing with . Keychain permission: Posting. Hive Keychain will ask you to approve this action next.


  
Technical details

Operation fingerprint: