Bentley
Bentley

Reputation: 153

Dynamically load subdomains folder as root with .htaccess

I'm trying to achieve, using .htaccess, so I can access all my projects with the configurations of one virtual host setup, and one URL defined in the hosts file. This will allow me to drop a project in the folder and it will function without having me to do any other configurations, and save a lot of time while working.

Example A: prestige.projects.dev is hosted on D:/projects/prestige etc.

Example B: newproject.projects.dev is hosted on D:/projects/newproject etc.

The code below works for the specific situation of Example A, but I can't figure out how to make it work 'dynamically' for all projects. My goal is to make prestige a wildcard. For example: newproject.projects.dev should automatically load the contents of D:/projects/newproject.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^prestige\.projects\.dev$
RewriteCond %{REQUEST_URI} !^/prestige/
RewriteRule (.*) /prestige/$1

I'm open to other suggestions than this method, as long as the goal is achieved.

Upvotes: 2

Views: 154

Answers (1)

MrWhite
MrWhite

Reputation: 45829

Try something like the following instead:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^([a-z]+)\.projects\.dev [NC]
RewriteCond "%{REQUEST_URI} /%1" !^(/[^/]+)[^\s]*\s\1$
RewriteRule (.*) /%1/$1 [L]

%1 is a backreference to the captured group in the last matched CondPattern.

The second RewriteCond directive is the "wildcard" version of your hardcoded check to make sure the REQUEST_URI does not already start with the directory that matches the subdomain - thus preventing a rewrite loop.

The string %{REQUEST_URI} /%1 (which expands to a string of the form "/<directory>/<anything> /<subdomain>" after the first rewrite) is matched against the regex ^(/[^/]+)[^\s]*\s\1$, which checks to see if /<directory> is the same as /<subdomain (\1 being an internal backreference to the captured group in the regex). Only if this does not match then the RewriteRule substitution occurs - in the same way your current rule works.

Upvotes: 2

Related Questions