nginx可以使用server块来设置多个虚拟主机,在server段中用server_name和listen指令来绑定域名和端口。例如:
代码如下 |
复制代码 |
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;
}
}
|
上述配置就是指定了两个虚拟主机,分别是www.netingcn.com和www.netingcn.net。可能在某些nginx的版本中上述的配置并不能很好的工作,出现的情况是所有的请求都是由第一个server处理的。
造成这个的原因是没有配置一个”Catch All”的缺省server,所谓缺省即是把不匹配配置指定的虚拟主机的请求都交给缺省server来处理。缺省server的配置如下:
代码如下 |
复制代码 |
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;
}
|
Vps 上安装了 nginx。用多个子域名,每个子域名到不同的目录。
如:
代码如下 |
复制代码 |
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/;
}
}
}
|
结果发现用 b.chenlb.com 还是指到 host_a 目录。后来看了官方示例:http://wiki.nginx.org/NginxVirtualHostExample,提到有个 default 的匹配,如:
代码如下 |
复制代码 |
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;
}
}
}
|
加上这个 default 就可使 a.chenlb.com 和 b.chenlb.com 正常工作了。