温馨提示×

Ubuntu Apache2怎么优化性能

小樊
47
2026-09-23 12:24:31
栏目: 智能运维

在 Ubuntu 上优化 Apache2 性能,通常可以从 MPA/MPM 配置、模块精简、缓存、系统参数、静态资源、PHP/FPM 等方面入手。下面按「实用优先」给你一套常见优化方案。


一、选择并优化 MPM(最重要)

Apache 有三种 MPM:

  • prefork(进程型,兼容老 PHP)
  • worker(线程型)
  • event(推荐,高并发)

查看当前 MPM

apachectl -V | grep -i mpm

推荐:使用 event MPM

sudo a2dismod php*
sudo a2enmod mpm_event
sudo systemctl restart apache2

调整 MPM 参数

编辑:

sudo nano /etc/apache2/mods-enabled/mpm_event.conf

示例(2核4G服务器):

<IfModule mpm_event_module>
    StartServers             2
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadLimit             64
    ThreadsPerChild         25
    MaxRequestWorkers      150
    MaxConnectionsPerChild 1000
</IfModule>

内存小就降低 MaxRequestWorkers


二、关闭不必要的模块

查看已启用模块:

apache2ctl -M

常见可关闭:

sudo a2dismod autoindex status cgi negotiation userdir
sudo systemctl restart apache2

三、开启压缩(Gzip / Brotli)

启用 Gzip

sudo a2enmod deflate
sudo a2enmod headers

编辑:

sudo nano /etc/apache2/conf-available/deflate.conf

示例:

AddOutputFilterByType DEFLATE text/html text/css application/javascript
sudo a2enconf deflate
sudo systemctl restart apache2

四、开启缓存(浏览器 + 磁盘)

浏览器缓存

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>

五、使用 PHP-FPM(强烈推荐)

比 mod_php 快很多。

sudo apt install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php-fpm
sudo a2dismod php*
sudo systemctl restart apache2

六、关闭 KeepAlive(视情况)

高并发短连接可关:

sudo nano /etc/apache2/apache2.conf
KeepAlive Off

或适度:

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

七、系统层面优化

文件描述符

ulimit -n

如太小:

sudo nano /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

TCP 参数(可选)

sudo nano /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
sudo sysctl -p

八、使用反向代理 / 静态分离(进阶)

  • 静态资源 → Nginx
  • 动态请求 → Apache
  • 或用 CDN

九、常用检测命令

top
htop
apachectl status
sudo tail -f /var/log/apache2/access.log

十、推荐基础组合(总结)

✅ event MPM
✅ PHP-FPM
✅ Gzip
✅ 浏览器缓存
✅ 精简模块
✅ 合理 MaxRequestWorkers


如果你愿意,可以告诉我:

  • 服务器配置(CPU/内存)
  • 是否用 PHP / WordPress
  • 访问量级别

我可以给你一套针对性配置。

0 踩