nginx的主配置文件为nginx.conf,主配置文件包含的所有虚拟主机的子配置文件会统一放入extra目录中,虚拟主机的配置文件按照网站的域名或功能取名,例如www.conf、bbs.conf、blog.conf等。当然,如果虚拟主机的数量不是很多,也可以把多个虚拟主机配置成一个单独的配置文件,仅仅和nginx的主配置文件 nginx.conf分离开即可。
这里使用的参数是include,下面先看看它的语法:
include file | mask
它可以放置在nginx配置中的任何位置。用法示例如下:
include mime.types; include www.conf; #包含单个文件; include vhosts/*.conf 包含vhosts下所有以conf结尾的文件;
下面是nginx配置的实战方案,具体如下:
#以基于域名的虚拟主机为例:
[root@nginx conf]# mkdir extra
[root@nginx conf]# egrep -v "#|^$" nginx.conf.default >nginx.conf #过滤包含#号和空行,生成新文件nginx.conf
查看新生成的nginx配置文件
[root@nginx conf]# cat -n nginx.conf
1 worker_processes 1;
2 events {
3 worker_connections 1024;
4 }
5 http {
6 include mime.types;
7 default_type application/octet-stream;
8 sendfile on;
9 keepalive_timeout 65;
10 server {
11 listen 80;
12 server_name localhost;
13 location / {
14 root html;
15 index index.html index.htm;
16 }
17 error_page 500 502 503 504 /50x.html;
18 location = /50x.html {
19 root html;
20 }
21 }
22 }
#把10-21行的虚拟主机配置内容分别写到extra/dmtest1.conf,extra/dmtest2.conf和extra/dmtest3.conf文件中,并做修改
[root@nginx conf]# sed -n ‘10,21p‘ nginx.conf >extra/dmtest1.conf
[root@nginx conf]# sed -n ‘10,21p‘ nginx.conf >extra/dmtest2.conf
[root@nginx conf]# sed -n ‘10,21p‘ nginx.conf >extra/dmtest3.conf
[root@nginx conf]# cat extra/dmtest1.conf
server {
listen 80;
server_name localhost;
location / {
root html/dmtest1; #站点目录修改为html/dmtest1;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
[root@nginx conf]# cat extra/dmtest2.conf
server {
listen 80;
server_name localhost;
location / {
root html/dmtest2; #站点目录修改为html/dmtest2;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
[root@nginx conf]# cat extra/dmtest3.conf
server {
listen 80;
server_name localhost;
location / {
root html/dmtest3; #站点目录修改为html/dmtest1;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
原文:https://www.cnblogs.com/Mr-Ding/p/9535843.html