2

I have a question concerning the setup of nginx on a server handling different virtual hosts. I am now a bit confused where the root directive should be. I have seen the following two possibilities.

Variant A

server {
listen          80;
server_name     www.site.com;
access_log      /var/log/nginx/www.site.com.access.log main;
root            /var/www/$server_name/htdocs;

location / {
   index index.html;
   }
}

or the other one

Variant B

server {
listen          80;
server_name     www.site.com;
access_log      /var/log/nginx/www.site.com.access.log main;

location / {
   root         /var/www/$server_name/htdocs;
   index        index.html;
   }
}

I am a bit confused if the two variants are equal. For the different vhosts I planned to have individual .conf files with different server_name and root directives in /etc/nginx/sites-available. To activate a vhost I would have a symbolic link to the conf file in /etc/nginx/sites-enabled. Or would you store the configuration file in /var/www/$server_name to have it "close" to the www data?

So to sum up, I have two questions:
1. Which of the two variants of the nginx.conf file is better for the multiple vhost setup and why?
2. Where would you store the configuration files for each vhost?

Thanks.

2

Variant A is the proper way to do it. Nginx will only ever use one location block so if you define root in a location it will only be available in that location. This almost always leads to duplication of either root directives of file paths, neither of which is good.

If you define it in the server block it is always inherited by the location blocks so it will always be available in the $document_root variable, thus avoiding the duplication of file paths.

  • Thank you so much for this! It make perfect sense, of course, but runs counter to all of the bad examples on the net. Most egregiously, the official "Beginner's Guide" at nginx.org/en/docs/beginners_guide.html is not doing anybody any favors by having EVERY SINGLE example show root directives in location blocks! – DaveGauer Jun 25 '15 at 21:14
  • I get the $document_root variable cannot be used in the "alias" directive when trying to use that variable in a location ... { alias ... }, so I still have to use an absolute path. – Dan Dascalescu Jun 7 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.