Max Bündchen
Max Bündchen

Reputation: 1352

Using Rewritebase in .htaccess

I'm using a .htaccess to redirect all calls to http://domain/site1/api/ to index.php in /site1/api/ folder. This index.php is the entry point for a rest api.

# /site1/api/.htaccess
RewriteEngine On
RewriteBase /site1/api/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

It works fine, but is there a better way than use a hard coded RewriteBase? I would like to this two urls work: http://site1.domain/api/ and http://domain/site1/api/.

Upvotes: 0

Views: 272

Answers (1)

Jon Lin
Jon Lin

Reputation: 143856

You can sort of create a dynamic base using environment variables. So at the very top of your htaccess, maybe something like this:

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

So the "BASE" variable becomes /site1/api/. And you'd then use it like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ %{ENV:BASE}/index.php [QSA,L]

Upvotes: 3

Related Questions