Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Let .htaccess RewriteRule redirect to a script "in current dir" (instead of an explicit path)

I'm using a RewriteRule in .htaccess to redirect anything that is not an existing file, to a "cms.php" file which dynamically handles any request (or outputs some error message if appropriate).

Here's what I do in .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /cms.php [L,QSA]

Works like a charm.

However, for development purposes, I want to host the same site on my local XAMPP system as well. On my actual live webserver, the cms.php is right in de document root folder, hence I can use /cms.php there. But on my local development machine, this site is in some subdir, i.e. /cms.php is not the right path.

I also tried "cms.php" (without the / in front of it) as well as "./cms.php" (hoping that "." would denote the current dir) but to no avail. Only when I explicitly specify /the/correct/subdir/cms.php in the RewriteRule, it works OK, but obviously this is only valid on the development machine and not on my live webserver.

Can I somehow use a smart path or mod_rewrite variable or something, so that .htaccess understands it needs to redirect to my cms.php file in the same dir as where .htaccess itself resides ?

like image 900
Sheldon Pinkman Avatar asked Jan 09 '14 17:01

Sheldon Pinkman


1 Answers

Typically, you'd just set a RewriteBase to the dev directory and leave the leading slash off of your rule's target:

RewriteEngine On
RewriteBase /subdir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ cms.php [L,QSA]

But if that's not good enough, and you want to be able to move the htaccess file around arbitrarily without having to alter the base all the time, ou can try to do something crazy by detecting an arbitrary base:

RewriteCond %{ENV:URI} ^$
RewriteRule ^(.*)$ - [ENV=URI:$1]

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

at the very top of your htaccess file, then using the BASE environtment variable:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}cms.php [L,QSA]
like image 169
Jon Lin Avatar answered Nov 11 '22 11:11

Jon Lin