温馨提示×

Debian Apache2虚拟主机怎么配置

小樊
35
2025-12-21 20:25:02
栏目: 云计算

Debian Apache2 虚拟主机配置步骤

一 准备与安装

  • 更新索引并安装 Apache:sudo apt update && sudo apt install apache2
  • 启动并设置开机自启:sudo systemctl start apache2 && sudo systemctl enable apache2
  • 启用常用模块(伪静态与 SSL):sudo a2enmod rewrite && sudo a2enmod ssl
  • 防火墙放行(如使用 UFW):sudo ufw allow ‘Apache Full’(或分别放行 80/443 端口)

二 创建站点目录与权限

  • 建议目录结构:/var/www/example.com/public_html(也可直接用 /var/www/example.com)
  • 创建目录并设定属主与权限:
    • sudo mkdir -p /var/www/example.com/public_html
    • sudo chown -R www-data:www-data /var/www/example.com
    • sudo chmod -R 755 /var/www/example.com
  • 创建测试首页:echo “

    Welcome to example.com

    ” | sudo tee /var/www/example.com/public_html/index.html

三 新建虚拟主机配置文件

  • 配置文件路径:/etc/apache2/sites-available/example.com.conf
  • 示例内容(基于域名,端口 80):
    • <VirtualHost *:80>
      • ServerAdmin webmaster@example.com
      • ServerName example.com
      • ServerAlias www.example.com
      • DocumentRoot /var/www/example.com/public_html
      • <Directory /var/www/example.com/public_html>
        • Options -Indexes +FollowSymLinks
        • AllowOverride All
        • Require all granted
      • ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
      • CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
  • 说明:
    • 使用独立日志便于排错与审计
    • -Indexes 可防止目录列表,生产环境推荐开启
    • 若不使用 public_html,可将 DocumentRoot 与 Directory 指向 /var/www/example.com

四 启用站点与生效

  • 启用站点:sudo a2ensite example.com.conf
  • 可选:禁用默认站点:sudo a2dissite 000-default.conf
  • 语法检查:sudo apachectl configtest
  • 使配置生效:sudo systemctl reload apache2(或 restart)

五 DNS 与 HTTPS 配置

  • DNS 解析:在域名注册商控制台添加 A 记录 将域名指向服务器 IP;本地测试可临时编辑 /etc/hosts 添加解析条目
  • 申请并配置免费 SSL(Certbot + Apache 插件):
    • 安装:sudo apt install certbot python3-certbot-apache
    • 获取并自动配置证书:sudo certbot --apache -d example.com -d www.example.com
    • Certbot 会自动创建 HTTPS 虚拟主机并配置自动续期
  • 验证:访问 http://example.com 与 https://example.com,确认证书与站点正常

六 常见问题与排查

  • 403 Forbidden:检查 DocumentRoot 目录是否存在、权限是否为 www-data:www-data 且目录权限 755,以及 中是否包含 Require all granted
  • 404 Not Found:确认 DocumentRoot 路径与测试文件路径一致,默认首页文件名与 DirectoryIndex 设置匹配
  • 域名访问不到:核对 DNS 的 A 记录 是否已生效(可用 dig/nslookup 检查),以及云厂商安全组/本机防火墙是否放行 80/443
  • 端口占用:使用 sudo ss -tulpen | grep ‘:80|:443’ 排查占用进程
  • 语法或包含错误:sudo apachectl configtest 与 sudo journalctl -xeu apache2 定位问题

0