温馨提示×

如何快速配置Ubuntu Apache2

小樊
44
2026-08-16 13:01:59
栏目: 智能运维

下面给你一个快速配置 Ubuntu Apache2 的实用步骤,适合刚装完系统或需要快速搭建 Web 服务的情况(以 Ubuntu 20.04 / 22.04 为例)。


一、安装 Apache2

sudo apt update
sudo apt install apache2 -y

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


二、检查 Apache 状态

sudo systemctl status apache2

正常应看到 active (running)

常用命令:

sudo systemctl start apache2    # 启动
sudo systemctl stop apache2     # 停止
sudo systemctl restart apache2  # 重启
sudo systemctl enable apache2   # 开机自启

三、防火墙放行(如有 UFW)

sudo ufw allow 80        # HTTP
sudo ufw allow 443       # HTTPS
sudo ufw reload

验证:

sudo ufw status

四、测试默认站点

浏览器访问:

http://服务器IP

看到 Apache2 Ubuntu Default Page 即成功。


五、快速配置一个网站(示例)

1️⃣ 创建网站目录

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

2️⃣ 创建测试页面

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

3️⃣ 设置权限

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

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

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

内容示例:

<VirtualHost *:80>
    ServerAdmin admin@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>

七、启用站点并重启

sudo a2ensite example.com.conf
sudo a2dissite 000-default.conf   # 可选:禁用默认站点
sudo systemctl reload apache2

八、启用伪静态(如需要)

sudo a2enmod rewrite
sudo systemctl restart apache2

九、常见目录速查

作用 路径
主配置 /etc/apache2/apache2.conf
虚拟主机 /etc/apache2/sites-available/
启用站点 /etc/apache2/sites-enabled/
网站根目录 /var/www/
日志 /var/log/apache2/

十、常见问题速排

403 Forbidden
→ 目录权限或 <Directory> 配置错误

端口被占用

sudo netstat -tlnp | grep 80

修改配置不生效

sudo apache2ctl configtest
sudo systemctl reload apache2

如果你需要:

  • HTTPS(Let’s Encrypt)
  • PHP / Python / 反向代理
  • 多站点配置
  • Docker 中配置 Apache

可以直接告诉我你的使用场景,我可以给你更精简或定制化的配置方案

0