温馨提示×

centos上apache怎么优化

小樊
48
2026-09-06 02:29:33
栏目: 智能运维

在 CentOS 上优化 Apache(通常是 httpd),可以从系统层面、Apache 配置、模块、缓存、安全与监控几个方面入手。下面是一套比较实用、可落地的优化思路(以 CentOS 7/8 + Apache 2.4 为例)。


一、基础环境与系统优化

1. 关闭或调整 SELinux(按需)

getenforce
# 若为 Enforcing 且不影响业务,可设为 Permissive
setenforce 0
# 永久关闭需修改 /etc/selinux/config

2. 文件描述符限制

ulimit -n 65535

修改 /etc/security/limits.conf:

* soft nofile 65535
* hard nofile 65535

3. 内核参数(/etc/sysctl.conf)

net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
sysctl -p

二、Apache 运行模式选择(非常重要)

推荐:event 或 worker(高并发)

httpd -V | grep -i mpm

修改 MPM 配置(CentOS 一般在):

/etc/httpd/conf.modules.d/00-mpm.conf

示例(event MPM):

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

经验值:

  • 内存小:worker
  • 高并发静态/API:event
  • 老程序(非线程安全):prefork

三、Apache 核心配置优化

1. 主配置文件 httpd.conf

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

Timeout 60
ServerTokens Prod
ServerSignature Off

四、启用与优化缓存

1. 开启 mod_deflate(压缩)

a2enmod deflate   # CentOS 通常是已编译

配置:

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

2. 开启 mod_expires(浏览器缓存)

<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>

五、禁用不必要的模块

减少内存与攻击面:

httpd -M

常见可禁用:

  • mod_userdir
  • mod_status(公网不建议开)
  • mod_autoindex

六、静态资源与反向代理优化

1. 静态文件走 Apache,动态走后端

ProxyPass /api/ http://127.0.0.1:8080/
ProxyPassReverse /api/ http://127.0.0.1:8080/

2. 使用 mod_cache(可选)

CacheEnable disk /
CacheRoot /var/cache/httpd

七、日志优化

1. 减少日志量

CustomLog logs/access_log combined env=!dontlog
SetEnvIf Request_URI "\.(jpg|css|js)$" dontlog

2. 日志轮转

/etc/logrotate.d/httpd

八、安全与稳定性

<Directory />
    AllowOverride None
    Require all denied
</Directory>

<Files ".ht*">
    Require all denied
</Files>

九、监控与压测

1. 查看状态

systemctl status httpd
apachectl -t

2. 压测工具

ab -n 10000 -c 200 http://localhost/

十、常见性能问题排查顺序

  1. 是否是 MPM 不对(prefork 吃内存)
  2. 是否 KeepAlive 时间过长
  3. 是否模块过多
  4. 是否磁盘 IO / 数据库慢
  5. 是否后端(PHP/Java)慢

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

  • CentOS 版本
  • Apache 版本
  • 网站类型(PHP / 静态 / 反向代理)
  • 内存大小

我可以给你一套直接可用的配置文件。

0 踩