1

English is not my native language, please accept my apologies for any language issues.

I want a configuration with automatic root, regardless of domain, look like this (using nginx):

root /var/www/${http_host}/public

But I want the root domain and the "www" to point to the same directory, but without the "www":

Example:

  1. "www.mysite.com" and "mysite.com"

    root /var/www/mysite.com/public

  2. But "blog.mysite.com"

    root /var/www/blog.mysite.com/public


That is, only the "www" should point to the directory that does not have "www" in the name.

Yes I saw that there are other similar questions (like this one), but I had difficulty removing the "www". Excuse me!

I will not use such a generic server_name, but this should work even with:

server_name ~.+$;

But also so:

listen 443 ssl http2;

server_name ~ ^((www|blog|account|bbs)\.)?mysite.com$;

root /var/www/${http_host}/public

ssl_certificate /ssl/${http_host}/{http_host}.pem
ssl_certificate_key /ss/${http_host}/{http_host}.key

NOTE: It should work with from the ssl certificate path.

guinalz
  • 11
  • 3
  • I wonder if you could assign the non-www part of the http_host variable to a new variable using a regular expression capture group. Regular expression might be something like "^([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$" (without speech marks), but I don't know off the top of my head how to assign this to a variable. – Tim Jan 26 '17 at 00:57

1 Answers1

3

You can use a map in the http block like this:

map $http_host $rootdir {
    ~^(?:www\.)?(?<domain>.+)$ $domain;
}

And then you use the following in your server block:

root /var/www/${rootdir}/public;

In the map directive, we convert $http_host variable containing the HTTP request Host header to $rootdir using the regular expression.

In the regular expression we extract the actual domain name to the $domain variable from the Host header by excluding www. prefix if it exists. We then use the $domain variable to build the $rootdir variable.

However, this method might not work with SSL due to reasons mentioned in the comment. In this case you need to implement a configuration management system which generates configuration files for domains from templates.

Tero Kilkanen
  • 34,499
  • 3
  • 38
  • 58
  • I'm not sure about SSL though, AFAIK NGINX loads all certificates at boot time and drops privileges afterwards so this most likely won't work on SSL with multiple certificates. – Ginnungagap Jan 26 '17 at 07:01
  • Good point, with SSL there might be no way to implement this except a configuration management system. I updated the answer, thanks. – Tero Kilkanen Jan 26 '17 at 12:17