.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#%{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!
Leave .htaccess mod_rewrite trick - Dynamic RewriteBase to:
Read more #apache posts
Best Posts From Stormrider Studios
We have not curated any of stormriderstudio's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Stormrider Studios
- Playing with F.I.R.E - Part 1
- Playing with F.I.R.E - Part 1
- So where do I go from here?
- Has it really been 3 years???
- Charity Competition #1 - Winner!
- Charity Competition #1 - Win SBD for a good cause!
- Soppy memeing to my wife... sick bags on standby!
- .htaccess mod_rewrite trick - Dynamic RewriteBase
- To those who worry about me
- Great start to the morning
- Python for Parents - Part 1: Hello World!
- When I find myself in times of trouble...
- Cold Hard Cash...
- Sorry to anyone wanting to sell SBD this week...
- Operation Minnow: Status check
- It's cold outside...
- The big battle MKII (roughly $100'000 on the line)
- Next BIG battle in Eve Online has started!
- The maggot at the core of the Steemit apple
- A Carrier is born!