Serve website root dynamically based on domain nam

2019-09-18 11:14发布

问题:

I have a server where I host multiple domain names. Depending on the domain name I'd like to serve files for a corresponding directory based on that domain name. For example:

www.domainA.com serves files from /var/www/html/domainA.com

www.domainB.com serves files from /var/www/html/domainB.com

etc. This way I do not have to edit my config file every time I add a site. In Apache I did it like this:

RewriteEngine on
RewriteMap    lowercase int:tolower
RewriteCond   ${lowercase:%{HTTP_HOST}}   ^(www\.)?(.*)$
RewriteRule   ^(.*) /var/www/html/%2/$1

How can I do the same thing in nginx?

回答1:

Capture the domain name from the $host variable using a map outside of your server block.

map $host $domain_name {
   ~(?<domain>[^.]+\.[^.]+)$ $domain;
}

Then add the new $domain_name variable to your root statement. Note that $host is normalized to lowercase, so your domain directories should also be lowercase.

root  /var/www/html/$domain_name;

Make sure you've setup the server as the default.



标签: nginx