温馨提示×

ubuntu apache怎样优化

小樊
38
2026-09-26 09:09:23
栏目: 智能运维

下面从 系统层、Apache 本身、PHP(如有)、缓存与架构 几个角度,系统地说一下 Ubuntu + Apache 的优化思路,适合生产环境参考。


一、系统层优化(基础)

1. 内核与文件描述符

ulimit -n

建议提高到:

* soft nofile 65535
* hard nofile 65535

写入 /etc/security/limits.conf

2. 关闭不必要的服务

systemctl disable bluetooth
systemctl disable cups

3. 使用 SSD & 足够内存

  • Apache 对内存敏感
  • 推荐:
    • 静态站点:1G+
    • PHP/动态:2G+

二、Apache MPM 选择与调优(最关键)

查看当前 MPM

apache2ctl -V | grep MPM

常见 MPM

MPM 场景
prefork 老 PHP(无线程安全)
worker 中等并发
event ✅ 推荐(高并发)

推荐:event MPM

a2dismod php*
a2enmod mpm_event

配置示例(/etc/apache2/mods-available/mpm_event.conf):

<IfModule mpm_event_module>
    StartServers             3
    MinSpareThreads         75
    MaxSpareThreads        250
    ThreadsPerChild         25
    MaxRequestWorkers      400
    MaxConnectionsPerChild 10000
</IfModule>

三、KeepAlive 优化

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

✅ 减少 TCP 握手
❌ 不要设太大(防止连接占用)


四、模块精简(非常重要)

查看已启模块

apache2ctl -M

建议关闭

a2dismod status
a2dismod autoindex
a2dismod cgi

只保留必要模块(如 rewrite、ssl、headers)


五、开启压缩与缓存

1. 启用 Gzip

a2enmod deflate
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>

2. 浏览器缓存

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 优化(如使用)

1. 使用 PHP-FPM(强烈推荐)

apt install php-fpm
a2enmod proxy_fcgi
a2enconf php-fpm

2. php.ini 调整

memory_limit = 256M
max_execution_time = 30
opcache.enable=1
opcache.memory_consumption=128

七、静态资源与架构优化

1. 静态文件走 Nginx(可选)

Apache 处理动态,Nginx 处理静态

2. 使用 CDN

  • 图片 / JS / CSS 放 CDN

3. 开启 HTTP/2

a2enmod http2

需 HTTPS


八、日志与监控

减少日志量

CustomLog /var/log/apache2/access.log combined env=!dontlog

监控工具

  • htop
  • apachetop
  • netdata

九、压测验证

ab -n 10000 -c 200 http://your-site/

十、推荐“标准生产配置”

✅ Ubuntu 22.04+
✅ Apache + mpm_event
✅ PHP-FPM
✅ Gzip + Expires
✅ HTTPS + HTTP/2


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

  • Ubuntu 版本
  • Apache 版本
  • 是否用 PHP / WordPress
  • 并发量大概多少

我可以给你 针对性优化配置。

0 踩