温馨提示×

ubuntu Apache如何配置

小樊
48
2026-07-05 23:10:08
栏目: 智能运维

下面给你一个在 Ubuntu 上配置 Apache(Apache2)的完整入门指南,从安装到常见配置,适合大多数 Web 服务器场景。


一、安装 Apache

sudo apt update
sudo apt install apache2

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

检查状态:

sudo systemctl status apache2

二、防火墙配置(非常重要)

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

sudo ufw allow 'Apache Full'

查看状态:

sudo ufw status

三、默认站点目录

  • 网站根目录
    /var/www/html
    
  • 默认首页
    index.html
    

测试: 浏览器访问:

http://服务器IP

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

1️⃣ 创建网站目录

sudo mkdir -p /var/www/example.com/public_html
sudo chown -R $USER:$USER /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️⃣ 测试并重载 Apache

sudo apache2ctl configtest
sudo systemctl reload apache2

五、启用 URL 重写(常见需求)

sudo a2enmod rewrite
sudo systemctl restart apache2

适用于 WordPress、Laravel 等框架。


六、配置 HTTPS(Let’s Encrypt)

1️⃣ 安装 Certbot

sudo apt install certbot python3-certbot-apache

2️⃣ 申请证书

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

证书会自动续期。


七、常用 Apache 命令

sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2
sudo systemctl reload apache2

八、常见配置文件位置

功能 路径
主配置 /etc/apache2/apache2.conf
虚拟主机 /etc/apache2/sites-available/
启用站点 /etc/apache2/sites-enabled/
模块配置 /etc/apache2/mods-available/
日志 /var/log/apache2/

九、常见问题排查

❌ 403 Forbidden

  • 目录权限错误
  • 没有 Require all granted

❌ 404 Not Found

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

❌ 端口被占用

sudo netstat -tulnp | grep :80

如果你有具体需求(如:部署 PHP、WordPress、Laravel、反向代理、多域名、HTTPS),可以直接告诉我,我可以给你针对性的 Apache 配置方案

0