本文共 1943 字,大约阅读时间需要 6 分钟。
在 Nginx 中,虚拟主机是处理多个域名或子域名请求的核心功能之一。以下将介绍如何配置默认虚拟主机以及如何为多个站点配置 Nginx。
默认虚拟主机是 Nginx 最基础的配置方式。当没有定义对应的域名或子域名时,请求将自动转向默认虚拟主机。
删除 nginx.conf 中的默认配置
打开/usr/local/nginx/conf/nginx.conf
文件,删除文件末尾的默认配置内容:server { listen 80; server_name localhost; index index.html index.htm index.php; root /usr/local/nginx/html; location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/tmp/php-fcgi.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name; }}
新增 include 语句
在文件末尾新增一行,告诉 Nginx 导入 vhost 目录下的配置文件:include vhost/*.conf;
创建 vhost 目录并新建默认配置文件
mkdir -p /usr/local/nginx/conf/vhost
/usr/local/nginx/conf/vhost/default.conf
并填写以下内容:server { listen 80 default_server; server_name aaa.com; index index.html index.htm index.php; root /data/wwwroot/aaa;}
创建站点文件夹并准备测试页面
mkdir -p /data/wwwroot/aaa
echo "this is aaa.com site" > /data/wwwroot/aaa/index.html
验证 Nginx 配置
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
测试访问
测试默认主机访问:
curl localhost
预期输出:this is aaa.com site
测试非存在域名访问:
curl -x 127.0.0.1:80 bbb.com
预期输出:this is aaa.com site
aaa.com
)。systemctl restart nginx
会清空旧的缓存文件,建议在新建配置后使用此命令。通过上述方法,我们已经配置好了默认虚拟主机。接下来将介绍如何为多个站点配置 Nginx。
进入 vhost 目录
cd /usr/local/nginx/conf/vhost
新建站点配置文件
abc.conf
)并填写以下内容:server { server_name abc.com; index index.html index.htm index.php; root /data/wwwroot/abc;}
创建站点主目录并准备测试页面
mkdir -p /data/wwwroot/abc
echo "abc.com" > /data/wwwroot/abc/index.html
测试访问
测试访问 abc.com
:
curl -x 127.0.0.1:80 abc.com
预期输出:abc.com
测试访问不存在的域名 cba.com
:
curl -x 127.0.0.1:80 cba.com
预期输出:this is aaa.com site
(默认虚拟主机响应)
通过以上配置,您已经成功搭建了 Nginx 的默认虚拟主机和多域名支持。默认虚拟主机自动处理未定义域名的请求,而多虚拟主机配置则允许您为不同域名设置独立的文件存储路径和访问权限。
转载地址:http://hyufk.baihongyu.com/