简体   繁体   中英

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM