1.为虚拟主机提供域名解析
echo "192.168.46.40 www.kgc.com www.benet.com" >> /etc/hosts
2.为虚拟主机准备网页文档
mkdir -p /var/www/html/benet
mkdir -p /var/www/html/kgc
echo "<h1>this is kgc.com</h1>" > /var/www/html/kgc/index.html
echo "<h1>this is benet.com</h1>" > /var/www/html/benet/index.html
3.修改Nginx的配置文件
vim /usr/local/nginx/conf/nginx.conf
......
http {
......
server {
listen 80;
server_name www.kgc.com; #设置域名www.kgc.com
charset utf-8;
access_log logs/www.kgc.access.log; #设置日志名
location / {
root /var/www/html/kgc; #设置www.kgc.com 的工作目录
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
server {
listen 80;
server_name www.benet.com; #设置域名www.benet.com
charset utf-8;
access_log logs/www.benet.access.log;
location / {
root /var/www/html/benet;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
}
4.重启服务,访问测试
nginx -t ##验证nginx配置文件是否正确
systemctl restart nginx
浏览器访问
http://www.kgc.com
http://www.benet.com
基于IP地址的Nginx虚拟主机
创建虚拟网卡
ifconfig ens33:1 192.168.46.80 netmask 255.255.255.0
修改Nginx配置文件
vim /usr/local/nginx/conf/nginx.conf
......
http {
......
server {
listen 192.168.46.40:80; #设置监听地址192.168.80.10
server_name www.kgc.com;
charset utf-8;
access_log logs/www.kgc.access.log;
location / {
root /var/www/html/kgc;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
server {
listen 192.168.46.80:80; #设置监听地址192.168.80.11
server_name www.benet.com;
charset utf-8;
access_log logs/www.benet.access.log;
location / {
root /var/www/html/benet;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
}
重新启动服务,测试
nginx -t
systemctl restart nginx
浏览器访问
http://192.168.80.10
http://192.168.80.11
基于端口的Nginx虚拟主机
修改配置文件
vim /usr/local/nginx/conf/nginx.conf
......
http {
......
server {
listen 192.168.46.80:808; #设置监听 808 端口
server_name www.kgc.com;
charset utf-8;
access_log logs/www.kgc.access.log;
location / {
root /var/www/html/kgc;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
server {
listen 192.168.46.40:88; #设置监听 88 端口
server_name www.benet.com;
charset utf-8;
access_log logs/www.benet.access.log;
location / {
root /var/www/html/benet;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
}
重启服务,测试
nginx -t
systemctl restart nginx
浏览器访问
http://192.168.80.11:8080
http://192.168.80.11:8888