优化 Ubuntu 上的 Apache 可以从系统层面、Apache 配置、模块与缓存、安全与监控几个方面入手。下面给你一套实用、可落地的优化方案,适合大多数生产/中型网站场景。
编辑 /etc/sysctl.conf:
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
fs.file-max = 100000
执行:
sysctl -p
ulimit -n 65535
并在 /etc/security/limits.conf 添加:
* soft nofile 65535
* hard nofile 65535
event MPM(Ubuntu 默认)a2query -M
如果不是 event:
sudo a2dismod php*
sudo a2enmod mpm_event
sudo systemctl restart apache2
如果用 PHP,建议配合 PHP-FPM,不要用 prefork
编辑:
/etc/apache2/mods-available/mpm_event.conf
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 10000
</IfModule>
按服务器内存调整(一般 2–4 GB 内存足够)
sudo a2enmod deflate
在 /etc/apache2/conf-available/deflate.conf:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
sudo a2enmod expires
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
sudo a2enmod cache cache_disk
<IfModule mod_cache.c>
CacheEnable disk /
CacheRoot /var/cache/apache2
CacheDirLevels 2
CacheDirLength 1
</IfModule>
查看已启用模块:
apache2ctl -M
常见可关闭:
sudo a2dismod status autoindex cgi
sudo apt install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php-fpm
php.ini 优化:
memory_limit = 128M
max_execution_time = 30
opcache.enable=1
LogLevel warn
或关闭访问日志(高并发时):
CustomLog /dev/null common
ServerTokens Prod
ServerSignature Off
sudo apt install apache2-utils
ab -n 1000 -c 100 http://localhost/
sudo a2enmod status
访问:http://server/ip-status
✅ 使用 mpm_event
✅ 开启 gzip
✅ 开启 expires
✅ 使用 PHP-FPM
✅ 关闭无用模块
✅ 调整 MaxRequestWorkers
✅ 开启 OPCache
如果你愿意,可以告诉我:
我可以给你定制化的 Apache 配置。