温馨提示×

Debian Apache如何优化

小樊
46
2026-07-21 18:04:47
栏目: 智能运维

下面给你一份Debian + Apache 的优化清单,从系统、Apache 配置、模块、PHP、缓存、安全、监控几个层面来,适合生产环境。


一、系统层面优化(基础)

1. 系统资源

# 查看内存、CPU
free -h
top

建议:

  • 内存 ≥ 2GB(小站 1GB 也可)
  • 关闭不必要的服务
systemctl disable bluetooth

2. 文件描述符限制

ulimit -n

修改:

vi /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

二、Apache MPM 选择(关键)

查看当前 MPM

apache2ctl -M | grep mpm

推荐方案

场景 MPM
静态站点 event
PHP-FPM event
老 PHP(mod_php) prefork

切换 MPM(Debian)

a2dismod mpm_prefork
a2enmod mpm_event
systemctl restart apache2

三、Apache 核心配置优化

1. MPM event 推荐配置

/etc/apache2/mods-available/mpm_event.conf

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

小内存服务器可降低 MaxRequestWorkers


2. KeepAlive 设置

/etc/apache2/apache2.conf

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

3. 关闭无用模块

apache2ctl -M

禁用示例:

a2dismod autoindex cgi status
systemctl restart apache2

四、PHP 优化(强烈推荐 PHP-FPM)

1. 安装 PHP-FPM

apt install php-fpm
a2enmod proxy_fcgi setenvif
a2enconf php8.x-fpm
systemctl restart apache2

2. PHP-FPM 配置

/etc/php/8.x/fpm/pool.d/www.conf

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20

五、缓存优化(性能提升明显)

1. 启用 Apache 缓存模块

a2enmod expires headers cache cache_disk
systemctl restart apache2

2. 示例缓存规则

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

六、启用 HTTP/2(可选)

a2enmod http2

虚拟主机中:

Protocols h2 http/1.1

⚠️ HTTP/2 需要 HTTPS


七、HTTPS & 安全优化

1. Let’s Encrypt

apt install certbot python3-certbot-apache
certbot --apache

2. 安全头

Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-Content-Type-Options "nosniff"
Header always set Content-Security-Policy "default-src 'self'"

八、日志优化(减少磁盘 IO)

1. 减少日志级别

LogLevel warn

2. 关闭访问日志(高并发可选)

CustomLog /dev/null combined

九、监控 & 压测

1. 查看 Apache 状态

a2enmod status
systemctl restart apache2

访问:

http://your-ip/server-status

2. 压测

apt install apache2-utils
ab -n 1000 -c 50 http://your-site/

十、推荐生产配置总结

✅ MPM event
✅ PHP-FPM
✅ 启用缓存
✅ 关闭无用模块
✅ HTTPS + HTTP/2
✅ 合理 KeepAlive
✅ 监控 server-status


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

  • 服务器配置(CPU / 内存)
  • 网站类型(WordPress / API / 静态)
  • 访问量级别

我可以给你一套针对你环境的精确配置

0