Nginx can use the server block to set multiple virtual hosts. In the server segment, use the server_name and listen commands to bind domain names and ports. For example:
The code is as follows: |
Copy code |
Server { Listen 80; Server_name www.netingcn.com; Location /{ Root netingcn_com; Index index.html; } } Server { Listen 80; Server_name www.netingcn.net; Location /{ Root netingcn_net; Index index.html; } } |
The preceding configuration specifies two virtual hosts: www.netingcn.com and www.netingcn.net. The above configuration may not work well in some nginx versions. In this case, all requests are processed by the first server.
This is because no "Catch All" default server is configured. By default, requests from the specified virtual host that do not match the configuration are handed over to the default server for processing. The default server configuration is as follows:
The code is as follows: |
Copy code |
Server { Listen 80 default_server; Server_name _; # This is just an invalid value which will never trigger on a real hostname. Access_log logs/default. access. log main; Server_name_in_redirect off; Root/var/www/default/htdocs; } |
Nginx is installed on Vps. Use multiple subdomains, each of which goes to a different directory.
For example:
The code is as follows: |
Copy code |
Http { Server { Listen 80; Server_name a.chenlb.com; Access_log logs/a. access. log main; Server_name_in_redirect off; Location /{ Index index.html; Root/home/www/host_a /; } } Server { Listen 80; Server_name B .chenlb.com; Access_log logs/B. access. log main; Server_name_in_redirect off; Location /{ Index index.html; Root/home/www/host_ B /; } } } Http { Server { Listen 80; Server_name a.chenlb.com; Access_log logs/a. access. log main; Server_name_in_redirect off; Location /{ Index index.html; Root/home/www/host_a /; } } Server { Listen 80; Server_name B .chenlb.com; Access_log logs/B. access. log main; Server_name_in_redirect off; Location /{ Index index.html; Root/home/www/host_ B /; } } } |
The result shows that B .chenlb.com still indicates the host_a directory. Next, let's take a look at the official example: http://wiki.nginx.org/nginxvirtualhostexample. a default match is found, for example:
The code is as follows: |
Copy code |
Http { Server { Listen 80 default; Server_name _; Access_log logs/default. access. log main; Server_name_in_redirect off; Location /{ Index index.html; Root/var/www/default/htdocs; } } Http { Server { Listen 80 default; Server_name _; Access_log logs/default. access. log main; Server_name_in_redirect off; Location /{ Index index.html; Root/var/www/default/htdocs; } } } |
Add this default to make a.chenlb.com and B .chenlb.com work normally.