温馨提示×

ubuntu apache如何优化

小樊
43
2026-09-11 02:49:43
栏目: 智能运维

在 Ubuntu 上对 Apache 进行优化,通常可以从 系统层面、Apache 配置、模块精简、缓存与压缩、安全与连接数 几个方面入手。下面给你一套实用、可落地的优化方案。


一、系统层面优化

1. 调整内核参数(TCP / 文件句柄)

编辑 /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

2. 提高文件描述符限制

编辑 /etc/security/limits.conf:

* soft nofile 65535
* hard nofile 65535

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

1. 查看当前 MPM

apache2ctl -V | grep MPM

Ubuntu 默认通常是:

  • prefork(兼容好,但耗内存)
  • event(推荐,性能最好)

2. 切换到 event MPM(推荐)

sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2

3. event MPM 配置示例

编辑:

/etc/apache2/mods-enabled/mpm_event.conf
<IfModule mpm_event_module>
    StartServers             4
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadLimit             64
    ThreadsPerChild         25
    MaxRequestWorkers      400
    MaxConnectionsPerChild 10000
</IfModule>

根据内存调整:

  • 2G 内存:MaxRequestWorkers 150
  • 4G+:300–500

三、精简 Apache 模块

查看已启用模块

apache2ctl -M

常见可禁用的模块

sudo a2dismod autoindex status cgi negotiation userdir
sudo systemctl restart apache2

只保留你真正用到的模块(如 rewrite、ssl、headers)。


四、开启压缩与缓存

1. 启用 Gzip 压缩

sudo a2enmod deflate

编辑 /etc/apache2/mods-enabled/deflate.conf:

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml
    AddOutputFilterByType DEFLATE text/css application/javascript
    AddOutputFilterByType DEFLATE application/json
</IfModule>

2. 浏览器缓存(Cache-Control)

sudo a2enmod expires headers

示例:

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 30 days"
    ExpiresByType text/css "access plus 7 days"
    ExpiresByType application/javascript "access plus 7 days"
</IfModule>

五、KeepAlive 与超时优化

编辑:

/etc/apache2/conf-enabled/keepalive.conf
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

高并发场景:KeepAliveTimeout 2–5 更合适


六、静态资源与 PHP 优化

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

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

PHP-FPM 比 mod_php 更稳定、更省内存。


2. 禁用 .htaccess(性能提升明显)

在虚拟主机中:

<Directory /var/www/html>
    AllowOverride None
</Directory>

把规则写进 Apache 配置,而不是 .htaccess


七、日志优化

减少日志量

CustomLog ${APACHE_LOG_DIR}/access.log combined env=!dontlog
SetEnvIf Request_URI "\.(jpg|png|css|js)$" dontlog

八、安全与稳定性

  • 隐藏 Apache 版本
ServerTokens Prod
ServerSignature Off
  • 限制请求体大小
LimitRequestBody 10485760

九、性能检测工具

top
htop
apache2ctl -S
ab -n 1000 -c 100 http://localhost/

十、典型优化组合(推荐)

✅ Ubuntu 22.04
✅ Apache + mpm_event
✅ PHP-FPM
✅ Gzip + Expires
✅ 禁用 .htaccess
✅ 精简模块


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

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

我可以直接给你 一份可复制的优化配置。

0 踩