温馨提示×

ubuntu apache2支持哪些配置

小樊
48
2026-09-05 06:30:03
栏目: 智能运维

在 Ubuntu 上,Apache2(通常是通过 apt 安装的 Apache HTTP Server)支持非常丰富的配置。下面按配置位置 / 配置类型系统地给你梳理一下,适合入门和日常管理。


一、Apache2 配置文件结构(Ubuntu 特有)

Ubuntu 的 Apache2 配置目录在:

/etc/apache2/

主要文件和目录:

路径 作用
/etc/apache2/apache2.conf 主配置文件(全局配置)
/etc/apache2/ports.conf 监听端口(80 / 443)
/etc/apache2/mods-available/ 可用模块配置
/etc/apache2/mods-enabled/ 已启用模块(软链接)
/etc/apache2/sites-available/ 虚拟主机配置
/etc/apache2/sites-enabled/ 启用的虚拟主机
/etc/apache2/conf-available/ 额外配置
/etc/apache2/conf-enabled/ 启用的额外配置
/var/log/apache2/ 日志目录

二、常用核心配置项(apache2.conf)

1️⃣ 全局基础配置

ServerName www.example.com
ServerAdmin admin@example.com

2️⃣ 目录权限(非常重要)

<Directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

常见选项:

  • Options Indexes:目录列表
  • FollowSymLinks:允许软链接
  • AllowOverride:是否允许 .htaccess

三、虚拟主机(最常用)

1️⃣ 创建虚拟主机

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

示例:

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

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

    ErrorLog ${APACHE_LOG_DIR}/example_error.log
    CustomLog ${APACHE_LOG_DIR}/example_access.log combined
</VirtualHost>

2️⃣ 启用站点

sudo a2ensite example.conf
sudo systemctl reload apache2

四、模块支持(Ubuntu 特色)

查看已启用模块

apache2ctl -M

常用模块

sudo a2enmod rewrite     # URL重写
sudo a2enmod ssl         # HTTPS
sudo a2enmod headers     # HTTP头
sudo a2enmod proxy       # 反向代理
sudo a2enmod proxy_fcgi  # PHP-FPM

五、HTTPS / SSL 配置

启用 SSL

sudo a2enmod ssl
sudo a2ensite default-ssl

示例:

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

    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/example.crt
    SSLCertificateKeyFile /etc/ssl/private/example.key
</VirtualHost>

六、.htaccess 支持的配置

在允许 AllowOverride All 的目录中可用:

RewriteEngine On
RewriteRule ^old$ new [R=301,L]

ErrorDocument 404 /404.html

七、反向代理(常见于 API / 微服务)

<VirtualHost *:80>
    ProxyPass /api/ http://127.0.0.1:3000/
    ProxyPassReverse /api/ http://127.0.0.1:3000/
</VirtualHost>

八、性能 & 安全相关

限制访问

Require ip 192.168.1.0/24

隐藏版本

ServerTokens Prod
ServerSignature Off

超时

Timeout 60
KeepAlive On

九、日志配置

LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
ErrorLog ${APACHE_LOG_DIR}/error.log

十、常用管理命令

sudo systemctl start apache2
sudo systemctl restart apache2
sudo systemctl reload apache2
sudo apache2ctl configtest

如果你愿意,我可以:

  • ✅ 给你一份 生产环境推荐配置
  • ✅ 帮你写 WordPress / Laravel / Vue 的 Apache 配置
  • ✅ 对比 Nginx vs Apache

你主要用 Apache 做什么?

0 踩