跳到主要内容

[toc]

nginx虚拟主机

虚拟机主机概念

  • 虚拟主机就是在一台服务器上配置多个网站

虚拟主机分类

  • 基于IP的虚拟主机(浪费IP,没用)

  • 基于端口的虚拟主机

  • 基于域名的虚拟主机

配置nginx虚拟主机

基于域名的虚拟主机

编辑aaa.com.conf文件

cat > /etc/nginx/conf.d/aaa.com.conf <<EOF
server {
listen 80;
server_name aaa.com;

location / {
root /website/aaa;
index index.html;
}
}
EOF

编辑bbb.com.conf文件

cat > /etc/nginx/conf.d/bbb.com.conf <<EOF
server {
listen 80;
server_name bbb.com;

location / {
root /website/bbb;
index index.html;
}
}
EOF

检测nginx语法并重载nginx

$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

$ nginx -s reload

创建网站根目录

mkdir /website/{aaa,bbb}
echo "aaa.com" > /website/aaa/index.html
echo "bbb.com" > /website/bbb/index.html

绑定hosts

cat >> /etc/hosts <<EOF
127.0.0.1 aaa.com
127.0.0.1 bbb.com
EOF

测试访问

$ curl aaa.com
aaa.com

$ curl bbb.com
bbb.com

基于端口的虚拟主机

虚拟主机监听不同端口,不与系统端口冲突即可

编辑aaa.com.conf文件

cat > /etc/nginx/conf.d/aaa.com.conf <<EOF
server {
listen 8001;
server_name aaa.com;

location / {
root /website/aaa;
index index.html;
}
}

server {
listen 8002;
server_name aaa.com;

location / {
root /website/bbb;
index index.html;
}
}
EOF

检测nginx语法并重载nginx

$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

$ nginx -s reload

测试访问

$ curl aaa.com:8001
aaa.com

$ curl aaa.com:8002
bbb.com

配置虚拟主机别名

虚拟主机别名,就是虚拟主机设置除了主域名以外的一个域名,实现用户访问的多个域名对应同一个虚拟主机网站的功能。

编辑aaa.com.conf文件

cat > /etc/nginx/conf.d/aaa.com.conf <<EOF
server {
listen 80;
server_name aaa.com bbb.com ccc.com;

location / {
root /website/aaa;
index index.html;
}
}
EOF

测试访问,aaa.com、bbb.com、ccc.com访问到的是同一个网站的同一资源

$ curl aaa.com
aaa.com

$ curl bbb.com
aaa.com

$ curl ccc.com
aaa.com