虚拟主机配置在nginx/conf/nginx.conf
中,使用serve进行配置,server中各个参数的含义如下:
server {
listen 80; //虚拟主机监听的端口
server_name localhost; //虚拟主机域名
location / { //资源路径映射路径, "/"代表的是安装目录
root html; //资源目录,相对于nginx的安装目录,可以设置成绝对路径
index index.html index.htm; //如果访问不到则打开这个资源
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
Nginx虚拟主机配置有三种方式,分别是:基于域名,基于端口,基于IP。
基于域名的虚拟主机配置:
(1)nginx中的配置如下:
#虚拟主机1
server {
listen 80;
server_name www.bxp1.com;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
#虚拟主机2
server {
listen 80;
server_name www.bxp2.com;
location / {
root /home/bxp/Documents/doc/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
(2)在/etc/hosts
中配置域名映射
127.0.0.1 www.bxp1.com
127.0.0.1 www.bxp2.com
(3)重启nginx服务
systemctl restart nginx
基于端口的虚拟主机:
(1)nginx中的配置如下:
#虚拟主机1
server {
listen 8888;
server_name www.bxp1.com;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
#虚拟主机2
server {
listen 80;
server_name www.bxp1.com;
location / {
root /home/bxp/Documents/doc/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
(2)重启nginx服务
systemctl restart nginx
基于IP的虚拟主机:
首先要为主机虚拟出另一个IP,先通过ifconfig查看网络配置如下:
通过ifconfig虚拟主机IP:
//虚拟IP
sudo ifconfig bnep0:1 192.168.44.95 netmask 255.255.255.0
//删除虚拟的IP
sudo ifconfig bnep0:1 down
通过ifconfig查看虚拟后的结果:
接下来在server中进行虚拟主机配置:
server {
listen 192.168.44.94:80;
server_name 192.168.44.94;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 192.168.44.95:80;
server_name 192.168.44.95;
location / {
root /home/bxp/Documents/doc/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
重启nginx服务,注意这里需要先停止nginx服务,在重新启动才能生效。
systemctl stop nginx
systemctl start nginx
location配置
最后在简单的说一下server中location的配置,下面通过官方的例子进行说明,具体可以查看官方文档location配置
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /documents/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
[ configuration E ]
}
请求“/”匹配配置A, 请求“/index.html”匹配配置B, 请求“/documents/document.html”匹配配置C, 请求“/images/1.gif”匹配配置D, 请求“/documents/1.jpg”匹配配置E。