Nginx网络服务——虚拟主机设置
- 一、基于域名的 Nginx 虚拟主机
- 1.为虚拟主机提供域名解析
- 2.为虚拟主机准备网页文档
- 3.修改Nginx的配置文件
- 4.重启服务,访问测试
- 二、基于IP 的 Nginx 虚拟主机
- 1.设置虚拟主机IP
- 2.修改主配置文件
- 3.重启服务,访问测试
- 三、基于端口的 Nginx 虚拟主机
- 1.修改主配置文件
- 2.重启服务,访问测试
相比较Apache的虚拟主机设置,Nginx的设置是十分简便的只需要修改主配置中的相关配置就能实现虚拟主机的效果
一、基于域名的 Nginx 虚拟主机
1.为虚拟主机提供域名解析
echo "192.168.30.20 www.hss.com www.ztm.com" >> /etc/hosts
2.为虚拟主机准备网页文档
mkdir -p /var/www/html/ztm
mkdir -p /var/www/html/hss
echo "<h1>www.ztm.com</h1>" > /var/www/html/ztm/index.html
echo "<h1>www.hss.com</h1>" > /var/www/html/hss/index.html
3.修改Nginx的配置文件
vim /usr/local/nginx/conf/nginx.conf
......
http {
......
server {
listen 80;
server_name www.ztm.com; #设置域名www.ztm.com
charset utf-8;
access_log logs/www.ztm.access.log; #设置日志名
location / {
root /var/www/html/ztm; #设置www.ztm.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.hss.com; #设置域名www.hss.com
charset utf-8;
access_log logs/www.hss.access.log;
location / {
root /var/www/html/hss;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
}
4.重启服务,访问测试
重启服务
systemctl restart nginx
浏览器访问
http://www.ztm.com
http://www.hss.com
二、基于IP 的 Nginx 虚拟主机
1.设置虚拟主机IP
ifconfig ens32:0 192.168.30.22 netmask 255.255.255.0
2.修改主配置文件
vim /usr/local/nginx/conf/nginx.conf
......
http {
......
server {
listen 192.168.30.20:80; #设置监听地址192.168.30.20
server_name www.ztm.com;
charset utf-8;
access_log logs/www.ztm.access.log;
location / {
root /var/www/html/ztm;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
server {
listen 192.168.30.22:80; #设置监听地址192.168.80.22
server_name www.hss.com;
charset utf-8;
access_log logs/www.hss.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;
}
}
}
3.重启服务,访问测试
重启服务
systemctl restart nginx
浏览器访问
http://192.168.30.20
http://192.168.30.22
三、基于端口的 Nginx 虚拟主机
1.修改主配置文件
vim /usr/local/nginx/conf/nginx.conf
......
http {
......
server {
listen 192.168.30.10:8080; #设置监听 8080 端口
server_name www.ztm.com;
charset utf-8;
access_log logs/www.ztm.access.log;
location / {
root /var/www/html/ztm;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
server {
listen 192.168.30.10:8888; #设置监听 8888 端口
server_name www.hss.com;
charset utf-8;
access_log logs/www.hss.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;
}
}
}
2.重启服务,访问测试
systemctl restart nginx
浏览器访问
http://192.168.30.20:8080
http://192.168.30.22:8888