periklis
periklis

Reputation: 10188

Extract part of server name in Apache RewriteRule

Let's suppose that I have a file in the filesystem like this:

/documentroot/domains/foo/files/resource.html

I want to write a rule so that http://foo.example.com/resource.html serves the file /domains/foo/files/resource.html. But if the request URL is http://bar.example.com/resource.html, it should look inside /domains/bar/files/resource.html. What I've accomplished so far is this, which works correctly:

RewriteEngine On

RewriteCond "%{DOCUMENT_ROOT}/domains/foo/%{REQUEST_URI}" -f
RewriteRule ^ domains/foo/%{REQUEST_URI} [QSA,L]

How can I generalize this, for any domain name? I was thinking of applying a regular expression to the %{SERVER_NAME} variable, but I can't find a way to achieve this.

Upvotes: 1

Views: 345

Answers (1)

anubhava
anubhava

Reputation: 785266

You can use this rule:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^(?!www\.)([^.]+)\. [NC]
RewriteRule !^domains/ domains/%1/files%{REQUEST_URI} [L,NC]

Upvotes: 2

Related Questions