下面给你一套Ubuntu 下 Apache2 的常见优化配置方案,从系统、Apache 本身、到 PHP / HTTPS 场景,适合生产环境。可按需裁剪。
ulimit -n
生产环境建议:
ulimit -n 65535
永久生效(Ubuntu):
sudo vim /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
sudo vim /etc/sysctl.conf
推荐配置:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_tw_reuse = 1
生效:
sudo sysctl -p
查看当前 MPM:
apache2ctl -M | grep mpm
sudo a2enmod mpm_event
sudo a2dismod mpm_prefork
sudo a2dismod mpm_worker
sudo vim /etc/apache2/mods-available/mpm_event.conf
推荐配置(4 核 8G 示例):
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 10000
</IfModule>
原则:
MaxRequestWorkers = 并发上限ThreadsPerChild × ServerLimit ≈ MaxRequestWorkerssudo vim /etc/apache2/apache2.conf
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 3
高并发下 KeepAliveTimeout 不要太大
apache2ctl -M
常见可禁用:
sudo a2dismod autoindex cgi status userdir
sudo a2enmod cache cache_disk expires headers
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 7 days"
ExpiresByType image/jpeg "access plus 30 days"
ExpiresByType image/png "access plus 30 days"
ExpiresByType application/javascript "access plus 7 days"
</IfModule>
sudo a2enmod deflate
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
sudo apt install brotli
sudo a2enmod brotli
sudo a2enmod http2
虚拟主机中:
Protocols h2 http/1.1
SSLSessionCache shmcb:/run/apache2/ssl_scache(512000)
SSLSessionCacheTimeout 300
CustomLog /var/log/apache2/access.log combined env=!dontlog
或关闭:
CustomLog /dev/null combined
sudo apt install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.x-fpm
sudo vim /etc/php/8.x/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
apache2ctl -t
sudo systemctl restart apache2
ab -n 10000 -c 100 http://yourdomain.com/
| 项目 | 建议 |
|---|---|
| MPM | event |
| MaxRequestWorkers | 300–1000 |
| KeepAliveTimeout | 2–5 |
| Gzip | 开启 |
| HTTP/2 | 开启 |
| PHP | PHP-FPM |
| 日志 | 精简 |
| 缓存 | disk_cache + expires |
如果你愿意,可以告诉我:
我可以给你一套完全针对你环境的 Apache2 配置模板。