首页主机资讯Apache2虚拟主机Ubuntu怎么配置

Apache2虚拟主机Ubuntu怎么配置

时间2025-12-03 10:03:03发布访客分类主机资讯浏览977
导读:Ubuntu 上配置 Apache2 虚拟主机 一 准备与安装 更新索引并安装 Apache2: sudo apt update sudo apt install apache2 启动并设置开机自启: sudo systemctl...

Ubuntu 上配置 Apache2 虚拟主机

一 准备与安装

  • 更新索引并安装 Apache2:
    • sudo apt update
    • sudo apt install apache2
  • 启动并设置开机自启:
    • sudo systemctl start apache2
    • sudo systemctl enable apache2
  • 验证服务状态(应看到 Active: active (running)):
    • sudo systemctl status apache2
  • 如启用防火墙,放行 HTTP/HTTPS:
    • sudo ufw allow ‘Apache Full’

二 创建站点目录与示例页面

  • 创建网站根目录(以 example.com 为例):
    • sudo mkdir -p /var/www/example.com
  • 设置目录属主(便于当前用户写入):
    • sudo chown -R $USER:$USER /var/www/example.com
  • 写入测试首页:
    • echo “Welcome to Example.com” | sudo tee /var/www/example.com/index.html

三 新建虚拟主机配置文件

  • 新建配置文件:
    • sudo nano /etc/apache2/sites-available/example.com.conf
  • 写入以下内容(按需替换域名与目录):
    • < VirtualHost *:80>
      • ServerAdmin webmaster@example.com
      • ServerName example.com
      • ServerAlias www.example.com
      • DocumentRoot /var/www/example.com
      • < Directory /var/www/example.com>
        • 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
  • 说明:
    • 使用 显式授权访问,避免 403。
    • 为便于排错,建议为站点单独定义 ErrorLog/CustomLog

四 启用站点与生效配置

  • 启用站点:
    • sudo a2ensite example.com.conf
  • 可选:禁用默认站点(避免与新建站点冲突):
    • sudo a2dissite 000-default.conf
  • 语法检查与平滑重载:
    • sudo apachectl configtest
    • sudo systemctl reload apache2

五 DNS 解析与 HTTPS 配置

  • DNS 解析:
    • 在域名 DNS 管理添加 A 记录,将 example.comwww.example.com 指向服务器公网 IP
  • 申请并配置免费 SSL(Certbot + Apache 插件):
    • sudo apt install certbot python3-certbot-apache
    • sudo certbot --apache -d example.com -d www.example.com
    • 按向导选择是否重定向 HTTP→HTTPS,证书将自动续期。
  • 验证:
    • 访问 http://example.comhttps://example.com,确认证书生效与站点可访问。

六 常用排错与优化

  • 检查语法与服务状态:
    • sudo apachectl configtest
    • sudo systemctl status apache2
  • 查看错误日志定位问题:
    • sudo tail -f /var/log/apache2/error.log
  • 常用模块按需启用:
    • 重写规则:sudo a2enmod rewrite
    • SSL:sudo a2enmod ssl(配合证书使用)
  • 防火墙与云安全组:
    • 确保放行 80/443 端口(UFW 使用:sudo ufw allow ‘Apache Full’)。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Apache2虚拟主机Ubuntu怎么配置
本文地址: https://pptw.com/jishu/762098.html
Debian支持Go语言哪些特性 Apache2在Ubuntu上的默认路径

游客 回复需填写必要信息