在 Ubuntu 上,Apache2(通常是通过 apt 安装的 Apache HTTP Server)支持非常丰富的配置。下面按配置位置 / 配置类型系统地给你梳理一下,适合入门和日常管理。
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/ |
日志目录 |
ServerName www.example.com
ServerAdmin admin@example.com
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
常见选项:
Options Indexes:目录列表FollowSymLinks:允许软链接AllowOverride:是否允许 .htaccesssudo 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>
sudo a2ensite example.conf
sudo systemctl reload apache2
apache2ctl -M
sudo a2enmod rewrite # URL重写
sudo a2enmod ssl # HTTPS
sudo a2enmod headers # HTTP头
sudo a2enmod proxy # 反向代理
sudo a2enmod proxy_fcgi # PHP-FPM
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>
在允许 AllowOverride All 的目录中可用:
RewriteEngine On
RewriteRule ^old$ new [R=301,L]
ErrorDocument 404 /404.html
<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
如果你愿意,我可以:
你主要用 Apache 做什么?