在 Ubuntu 上,Apache(通常是 Apache2)支持非常丰富和灵活的配置。下面按常见分类给你一个较系统的说明,适合实际运维和使用。
Ubuntu 中 Apache 配置主要位于:
/etc/apache2/
├── apache2.conf # 主配置文件
├── ports.conf # 监听端口
├── mods-available/ # 可用模块
├── mods-enabled/ # 已启用模块(软链接)
├── sites-available/ # 虚拟主机配置
├── sites-enabled/ # 启用站点(软链接)
├── conf-available/ # 额外配置
├── conf-enabled/ # 启用配置
└── envvars # 环境变量
常用命令:
sudo a2ensite xxx # 启用站点
sudo a2dissite xxx # 禁用站点
sudo a2enmod xxx # 启用模块
sudo a2dismod xxx # 禁用模块
sudo systemctl reload apache2
支持的主要配置项包括:
ServerName www.example.com
ServerAdmin admin@example.com
ServerTokens Prod
ServerSignature Off
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
最常用功能之一。
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
支持:
启用模块:
sudo a2enmod ssl
示例:
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /etc/ssl/certs/example.crt
SSLCertificateKeyFile /etc/ssl/private/example.key
</VirtualHost>
常配合:
sudo a2enmod rewrite
RewriteEngine On
RewriteRule ^old.html$ new.html [R=301,L]
支持:
sudo a2enmod proxy proxy_http
ProxyPass /api/ http://127.0.0.1:3000/
ProxyPassReverse /api/ http://127.0.0.1:3000/
支持:
Require ip 192.168.1.0/24
Require all denied
<Files *.php>
Require all granted
</Files>
可结合:
LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog ${APACHE_LOG_DIR}/access.log common
ErrorLog ${APACHE_LOG_DIR}/error.log
支持:
Ubuntu Apache 支持大量模块,例如:
rewrite:URL重写ssl:HTTPSproxy / proxy_http:反向代理headers:HTTP头控制deflate / gzip:压缩cache / cache_disk:缓存php / php8.1:PHP支持auth_basic:基础认证(需 AllowOverride All)
Options -Indexes
ErrorDocument 404 /404.html
Redirect 301 /old /new
Ubuntu 上的 Apache 支持 虚拟主机、SSL、重写、代理、权限控制、日志、模块扩展 等几乎全部 Web 服务器功能,配置灵活且适合生产环境。
如果你有具体需求(比如:
✅ 配置 HTTPS
✅ 多站点
✅ 反向代理
✅ 限制 IP
✅ 性能优化)
可以直接告诉我,我可以给你完整可直接用的配置示例。