温馨提示×

apache2 ubuntu怎么加速

小樊
45
2026-09-29 08:35:36
栏目: 智能运维

在 Ubuntu 上加速 Apache2,可以从**系统层面、Apache 配置、缓存、网络、PHP(如有)**几个方向来做。下面按「实用程度」给你一套方案。


一、基础系统优化(必做)

1. 开启 KeepAlive

sudo nano /etc/apache2/apache2.conf

确保:

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

2. 关闭不必要的模块

sudo a2dismod autoindex status cgi
sudo systemctl restart apache2

二、MPM 调优(非常关键)

查看当前 MPM:

apache2ctl -V | grep MPM

推荐用 event(高并发)

sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2

编辑配置:

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   0
</IfModule>

三、开启缓存(立竿见影)

1. 启用 Apache 缓存模块

sudo a2enmod expires headers cache cache_disk
sudo systemctl restart apache2

2. 启用浏览器缓存

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

内容:

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType application/javascript "access plus 1 week"
</IfModule>

启用:

sudo a2enconf cache
sudo systemctl restart apache2

四、启用 Gzip 压缩

sudo a2enmod deflate
sudo nano /etc/apache2/mods-enabled/deflate.conf

确保包含:

AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript

重启:

sudo systemctl restart apache2

五、PHP 加速(如果是 PHP 网站)

1. 使用 PHP-FPM

sudo apt install php-fpm
sudo a2enmod proxy_fcgi setenvif
sudo a2enconf php8.1-fpm   # 按你的 PHP 版本
sudo systemctl restart apache2

2. 安装 OPcache

sudo apt install php-opcache

php.ini 中:

opcache.enable=1
opcache.memory_consumption=128
opcache.revalidate_freq=60

六、使用反向代理 / CDN(外部加速)

  • Cloudflare(强烈推荐)
  • Nginx 反代 Apache(静态资源交给 Nginx)

七、系统层面加速

1. 文件描述符限制

ulimit -n 65535

2. 使用 SSD + 足够内存

Apache 很吃 I/O。


八、快速检查性能

ab -n 1000 -c 100 http://your-site.com/

总结(推荐顺序)

  1. 用 mpm_event + PHP-FPM
  2. 开启 gzip + expires
  3. 用 Cloudflare
  4. 禁用无用模块
  5. 上 OPcache

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

  • Ubuntu 版本
  • Apache + PHP?还是静态站?
  • 服务器配置(CPU / 内存)

我可以给你一套精准配置。

0 踩