在Linux中可以对一个网卡创建多个IP(虚拟的IP),也就是说可以使用单个网卡里的虚拟IP来创建虚拟主机的效果。
首先在一个网卡上添加一个IP(必须要在同一个网卡上添加)
ifconfig #查看本机IP以及网卡名
在ens33这个网卡上添加一个172.25.0.25的虚拟IP
ip a add 172.25.0.25 dev ens33 #在ens33这个网卡上添加一个虚拟IP
添加了一个虚拟IP后就可以修改Nginx的配置文件,default.conf文件(或者自己额外创建一个配置文件,添加下面的配置信息。但要在/etc/nginx/config 这个路径下创建,这样Nginx才可以读取到这个配置文件)
vim /etc/nginx/conf.d/default.conf
server {
listen 172.25.0.1:80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /opt/code;
index index.html index.htm;
}
复制一份上面的配置文件,命名为default1.conf,并修改里面的内容,要跟上面的配置文件内容不一样(访问的IP以及路径)
###复制配置文件###
cp -p /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default1.conf
###修改刚刚复制好的配置文件###
vim /etc/nginx/conf.d/default1.conf
server {
listen 172.25.0.25:80; #修改IP
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/log/host.access.log main;
location / {
root /opt/app/code5; #修改文件路径
index index.html index.htm;
}
在default.conf文件中指定的路径中创建一个名为admin.html文件,作为访问172.25.0.1的路径内容
vim /opt/code/admin.html
<html>
<head>
<meta charset="utf-8">
<title>vincen</title>
</head>
<body>
<a>nginx</a>
<a>172.25.0.20</a>
</body>
</html>
在default1.conf文件中指定的路径创建一个名为admin.html文件,作为访问172.25.0.25的路径内容
vim /opt/app/code5/admin.html
<html>
<head>
<meta charset="utf-8">
<title>VINCEN</title>
</head>
<body>
<a>NGINX</a>
<a>172.25.0.25</a>
</body>
</html>
配置好以上文件后,先检查Nginx的配置语法是否会报错,如果出现下面的提示则说明上面的配置(default.conf和default1.conf)是没有问题的
nginx -tc /etc/nginx/nginx.conf
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
配置文件没问题后,就对Nginx服务进行重新加载,读取刚刚所配置的内容。一般来说,配置文件语法没有报错的话,重载也是不会报错的
nginx -s reload -c /etc/nginx/nginx.conf
使用本地浏览器访问在Linux上的两个不同IP,出现不一样的内容
访问两个不同IP显示出不同的网页内容,此时Nginx基于IP的虚拟主机成功