温馨提示×

ubuntu apache2如何配置

小樊
33
2026-07-05 23:12:09
栏目: 智能运维

下面给你一个在 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 reload apache2

二、防火墙配置(UFW)

如果启用了 UFW,需要放行 HTTP / HTTPS:

sudo ufw allow 80
sudo ufw allow 443
sudo ufw reload

验证:

sudo ufw status

三、默认站点测试

浏览器访问:

http://服务器IP

看到 Apache2 Ubuntu Default Page 说明成功。

默认网站目录:

/var/www/html

四、目录与权限配置

1️⃣ 修改网站根目录权限

假设你的网站目录是 /var/www/html

sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html

www-data 是 Apache 运行的用户


五、虚拟主机(VirtualHost)配置(重点)

1️⃣ 创建网站目录

sudo mkdir -p /var/www/example.com
sudo chown -R www-data:www-data /var/www/example.com

创建测试页面:

echo "Hello Apache" | sudo tee /var/www/example.com/index.html

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

sudo nano /etc/apache2/sites-available/example.com.conf

内容示例:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com

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

    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>

3️⃣ 启用站点

sudo a2ensite example.com.conf
sudo systemctl reload apache2

禁用默认站点(可选):

sudo a2dissite 000-default.conf

六、启用 rewrite(URL 重写)

很多程序(WordPress、Laravel)需要:

sudo a2enmod rewrite
sudo systemctl restart apache2

确保目录中:

AllowOverride All

七、配置 HTTPS(Let’s Encrypt)

1️⃣ 安装 Certbot

sudo apt install certbot python3-certbot-apache

2️⃣ 申请证书

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

3️⃣ 自动续期

sudo certbot renew --dry-run

证书有效期 90 天,自动续期已配置


八、修改 Apache 监听端口(可选)

1️⃣ 修改端口

编辑:

sudo nano /etc/apache2/ports.conf

例如:

Listen 8080

修改虚拟主机:

<VirtualHost *:8080>

2️⃣ 重启

sudo systemctl restart apache2

九、常见配置文件位置总结

功能 路径
主配置 /etc/apache2/apache2.conf
虚拟主机 /etc/apache2/sites-available/
已启用站点 /etc/apache2/sites-enabled/
模块配置 /etc/apache2/mods-available/
端口配置 /etc/apache2/ports.conf
日志 /var/log/apache2/
网站目录 /var/www/

十、常见问题排查

❌ 403 Forbidden

  • 目录权限不对
  • Directory 未配置 Require all granted

❌ 404 Not Found

  • DocumentRoot 路径错误
  • 文件不存在

❌ 网站打不开

sudo apache2ctl configtest
sudo journalctl -xe

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

  • ✅ 是 云服务器 / 本地
  • ✅ 是否 绑定域名
  • ✅ 是否 PHP / Python / 静态网站
  • ✅ Ubuntu 版本(20.04 / 22.04 / 24.04)

我可以给你更精确的配置方案

0