在nginx中如何创建虚拟主机
在nginx中,虚拟主机定义在server块中。可以分为基于域名(名字)的和基于ip的。
虚拟主机是一个由Nginx在单个云VPS或物理服务器上提供服务的网站。
在Nginx中创建基于名称的虚拟主机
在Nginx文档中,虚拟主机使用的是“服务器块”这个词,但是它们基本上是相同的东西,只是名字不同而已。
设置虚拟主机的第一步是在主配置文件(/etc/nginx/nginx.conf)或/etc/nginx/sites-available 中创建一个或多个服务器块
在 /etc/nginx/sites-available目录中文件名是任意的,不过一般使用站点域名来命名。
创建两个新文件:
/etc/nginx/sites-available/hellozhilu.com.conf
server {
listen 80;
server_name hellozhilu.com www.hellozhilu.com;
access_log /var/www/logs/hellozhilu.access.log;
error_log /var/www/logs/hellozhilu.error.log error;
root /var/www/hellozhilu.com/public_html;
index index.html index.htm;
}
/etc/nginx/sites-available/zhilujiaocheng.com.conf
server {
listen 80;
server_name zhilujiaocheng.com www.zhilujiaocheng.com;
access_log /var/www/logs/zhilujiaocheng.access.log;
error_log /var/www/logs/zhilujiaocheng.error.log error;
root /var/www/zhilujiaocheng.com/public_html;
index index.html index.htm;
}
设置配置文件权限
# chmod 660 /etc/nginx/sites-available/tecmintlovesnginx.com.conf # chmod 660 /etc/nginx/sites-available/nginxmeanspower.com.conf ### 如果是Debian 和ubuntu # chgrp www-data /etc/nginx/sites-available/tecmintlovesnginx.com.conf # chgrp www-data /etc/nginx/sites-available/nginxmeanspower.com.conf ### 如果是CentOS 和 RHEL # chgrp nginx /etc/nginx/sites-available/tecmintlovesnginx.com.conf # chgrp nginx /etc/nginx/sites-available/nginxmeanspower.com.conf
为日志创建目录
同时给Nginx用户读写权限:
# mkdir /var/www/logs # chmod -R 660 /var/www/logs ### 如果是Debian 和ubuntu # chgrp www-data /var/www/logs ### 如果是CentOS 和 RHEL # chgrp nginx /var/www/logs
启用虚拟主机
# ln -s /etc/nginx/sites-available/tecmintlovesnginx.com.conf /etc/nginx/sites-enabled/tecmintlovesnginx.com.conf # ln -s /etc/nginx/sites-available/nginxmeanspower.com.conf /etc/nginx/sites-enabled/nginxmeanspower.com.conf
在每个站点的主目录中创建一个index.html文件
/var/www/zhilujiaocheng.com/public_html/index.html和/var/www/hellozhilu.com//index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>hello nginx</title>
</head>
<body>
<h1>Hello Nginx!</h1>
</body>
</html>
测试Nginx配置并启动web服务器
# nginx -t && systemctl start nginx
将域名解析到服务器ip地址, 然后使用浏览器打开http://hellozhilu.com和http://zhilujiaocheng.com即可。
在Nginx中基于ip的虚拟主机
与基于名称的虚拟主机(所有主机都可以通过相同的IP地址访问)不同,基于IP的虚拟主机需要使用不同的IP:端口组合。
如果网卡不够(物理ip),我们可以使用虚拟ip
在CentOS 和 RHEL中创建虚拟ip
将 /etc/sysconfig/network-scripts/ifcfg-enp0s3重命名为 ifcfg-enp0s3:1
DEVICE="enp0s3:1" IPADDR=192.168.1.25
,并拷贝一份,命名为 ifcfg-enp0s3:2
DEVICE="enp0s3:2" IPADDR=192.168.1.26
然后重启网络服务
# systemctl restart networking
修改监听地址
将之前的listen 80;
分别改成
listen 192.168.1.25:80
和
listen 192.168.1.26:80
重新启动Nginx使更改生效
# systemctl restart nginx
现在就可以直接使用IP访问网站了
http://192.168.1.25http://192.168.1.26

