7.2.4 基础虚拟主机与站点配置
本节介绍基于 Nginx 的基础虚拟主机与站点配置方法,覆盖单站点、多站点、基于域名与端口的区分,以及常见目录与权限约定,为后续反向代理与负载均衡配置打基础。
1. 原理草图:请求如何命中站点#
2. 虚拟主机类型与使用场景#
- 基于域名(Server Name):多域名共享同一 IP/端口,最常用。
- 基于端口(Listen):同一 IP 不同端口区分站点。
- 基于 IP:多 IP 场景下绑定不同站点。
3. 环境准备与安装示例(以二进制包为例)#
# 1) 安装 Nginx
yum -y install nginx
# 2) 查看版本与编译参数
nginx -v
nginx -V
# 3) 启动并设置开机自启
systemctl enable --now nginx
# 4) 验证服务端口
ss -lntp | grep nginx
预期效果:80 端口处于 LISTEN 状态,浏览器访问服务器 IP 返回 Nginx 默认页面。
4. 基础站点配置要素#
server块定义一个站点。listen指定监听地址与端口。server_name指定域名匹配规则。root与index定义站点根目录与默认首页。location定义路径匹配与处理逻辑。
5. 基于域名的单站点完整示例#
# 创建站点目录与首页
mkdir -p /data/www/example
echo "hello example.com" > /data/www/example/index.html
# 新建站点配置文件
cat >/etc/nginx/conf.d/example.conf <<'EOF'
server {
listen 80;
server_name example.com www.example.com;
root /data/www/example;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
EOF
# 检查并加载配置
nginx -t
nginx -s reload
预期效果:绑定域名解析至服务器后,访问 http://example.com 显示 hello example.com。
命令解释
- nginx -t:检查配置语法与文件引用是否正确。
- nginx -s reload:平滑重载配置,连接不中断。
6. 多站点配置与默认站点#
# 站点A
mkdir -p /data/www/siteA
echo "siteA" >/data/www/siteA/index.html
cat >/etc/nginx/conf.d/siteA.conf <<'EOF'
server {
listen 80;
server_name a.example.com;
root /data/www/siteA;
index index.html;
}
EOF
# 默认站点:不匹配域名时直接丢弃
cat >/etc/nginx/conf.d/default.conf <<'EOF'
server {
listen 80 default_server;
server_name _;
return 444;
}
EOF
nginx -t && nginx -s reload
预期效果:访问未配置域名时直接断开(444)。
7. 基于端口的站点示例#
mkdir -p /data/www/app8080
echo "port 8080" >/data/www/app8080/index.html
cat >/etc/nginx/conf.d/port8080.conf <<'EOF'
server {
listen 8080;
server_name _;
root /data/www/app8080;
index index.html;
}
EOF
nginx -t && nginx -s reload
预期效果:访问 http://<IP>:8080 返回 port 8080。
8. 常用 location 匹配示例#
# 精确匹配
location = /favicon.ico { access_log off; }
# 前缀匹配
location /static/ {
alias /data/www/example/static/;
expires 7d;
}
# 正则匹配
location ~* \.(jpg|png|css|js)$ {
expires 30d;
access_log off;
}
9. 站点目录与权限约定#
- 建议目录结构:
/data/www/<site_name>
/data/logs/nginx/<site_name>.access.log - 确保 Nginx 运行用户对站点目录有读权限。
# 查看 Nginx 运行用户
ps -ef | grep nginx | head -n1
# 授权只读
chown -R nginx:nginx /data/www/example
chmod -R 755 /data/www/example
10. 配置检查与生效#
# 语法检查
nginx -t
# 查看加载的配置文件路径
nginx -T | head -n 20
# 平滑重载
nginx -s reload
11. 常见排错与解决#
1) 访问 404
# 检查 root 是否正确
grep -R "root /data/www/example" -n /etc/nginx/conf.d
# 检查文件存在
ls -l /data/www/example/index.html
解决:修正 root 或创建首页文件。
2) 访问命中默认站点
# 检查 server_name 是否匹配
nginx -T | grep -n "server_name"
解决:增加域名或使用通配 *.example.com。
3) reload 失败
# 查看语法错误与行号
nginx -t
解决:根据报错行修复配置。
12. 练习#
1) 为 test.example.com 创建站点目录与配置,首页内容为 hello test。
2) 配置一个端口 9090 的站点并返回 port 9090。
3) 配置默认站点返回 444,验证未匹配域名时连接被关闭。
4) 设置 /static/ 目录缓存 7 天,并验证响应头 Expires。