Allow me to explain this topic more clearly to help beginners understand it.
This is how virtual hosting in Nginx works.
In the Nginx main config file (/etc/nginx/nginx.conf
), there’s an http { ... }
block, which has the following two lines:
include /etc/nginx/conf.d/.conf;
include /etc/nginx/sites-enabled/;
This means that the /etc/nginx/nginx.conf file will fetch the configurations stored under /etc/nginx/conf.d/ and /etc/ngixn/sites-enabled/ directories.
A virtual host file can reside in either /etc/nginx/conf.d/ or /etc/nginx/sites-enabled/ directory. Actually, they can reside in any directory on the server, as long as there’s an include directive in /etc/nginx/nginx.conf file to fetch the configurations.
include /etc/nginx/what-ever-directory-name-you-want/;
A virtual host in Nginx starts with the server keyword.
server {
listen 80;
server_name example.com;
…
your_configurations;
…
}
In every server {…} block, you use the server_name
directive to designate the server name.
server_name domain1.com
You can have another server {…} block with a server_name of domain2.com
server_name domain2.com
When Nginx receives an HTTP request, it checks the host header in the request and compares it with the server_name
directives. If the host header looks like this:
host: domain1.com
Then Nginx will use the first server block (virtual host). If the host header looks like this:
host: domain2.com
Then Nginx will use the second server block.
So this is how virtual hosting in Nginx works. This is called named-based virtual hosting. All virtual hosts in Nginx can listen to the same public IP address.
There’s another type of virtual hosting called IP-based virtual hosting. Each virtual host listens to a different IP address. This is an old-fashion way to host multiple websites and rarely used now.