温馨提示×

怎样配置ubuntu apache2

小樊
44
2026-07-17 11:36:04
栏目: 智能运维

下面给你一份在 Ubuntu 上配置 Apache2 的完整入门指南,从安装到常见配置(虚拟主机、HTTPS、权限等),适合服务器或本地开发环境。


一、安装 Apache2

sudo apt update
sudo apt install apache2

安装完成后,Apache 会自动启动。

检查状态:

sudo systemctl status apache2

常用命令:

sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl enable apache2   # 开机自启

二、防火墙配置(如果有 UFW)

sudo ufw allow 'Apache Full'

查看:

sudo ufw status

浏览器访问:

http://服务器IP

看到 Apache2 Ubuntu Default Page 即成功。


三、Apache2 目录结构说明

路径 说明
/var/www/html 默认网站根目录
/etc/apache2/apache2.conf 主配置文件
/etc/apache2/sites-available/ 虚拟主机配置
/etc/apache2/sites-enabled/ 已启用的虚拟主机
/etc/apache2/mods-available/ 可用模块
/etc/apache2/mods-enabled/ 已启用模块
/var/log/apache2/ 日志目录

四、配置虚拟主机(推荐)

1️⃣ 创建网站目录

sudo mkdir -p /var/www/example.com/public_html

创建测试页面:

echo "<h1>Example.com</h1>" | sudo tee /var/www/example.com/public_html/index.html

设置权限:

sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www

2️⃣ 创建虚拟主机配置文件

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/public_html

    <Directory /var/www/example.com/public_html>
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

3️⃣ 启用站点

sudo a2ensite example.com.conf
sudo a2dissite 000-default.conf   # 禁用默认站点(可选)

4️⃣ 启用 rewrite 模块(常用)

sudo a2enmod rewrite
sudo systemctl restart apache2

五、配置 HTTPS(Let’s Encrypt)

1️⃣ 安装 Certbot

sudo apt install certbot python3-certbot-apache

2️⃣ 申请证书

sudo certbot --apache -d example.com -d www.example.com

证书会自动续期。


六、常见配置示例

✅ 禁止目录浏览

Options -Indexes

✅ 设置默认首页

DirectoryIndex index.php index.html

✅ 配置 PHP(如已安装)

sudo apt install php libapache2-mod-php
sudo systemctl restart apache2

七、排错建议

  • 查看错误日志:
tail -f /var/log/apache2/error.log
  • 检查配置语法:
sudo apache2ctl configtest
  • 确认端口未占用:
sudo netstat -tlnp | grep 80

八、示例:本地开发环境

sudo nano /etc/apache2/sites-available/local.conf
<VirtualHost *:80>
    ServerName local.test
    DocumentRoot /home/user/project

    <Directory /home/user/project>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
sudo a2ensite local.conf
sudo systemctl restart apache2

然后在 /etc/hosts 添加:

127.0.0.1 local.test

如果你愿意,可以告诉我:

  • Ubuntu 版本
  • 用途(生产 / 本地 / Docker)
  • 是否需要 PHP / Python / HTTPS

我可以给你一份完全定制化的 Apache2 配置方案

0