Apache优化CentOS服务器响应的关键策略
/etc/httpd/conf/httpd.conf中设置:KeepAlive On(启用)、MaxKeepAliveRequests 100(单连接最大请求数)、KeepAliveTimeout 5(连接超时时间,避免长期占用资源)。prefork,高并发推荐event/worker)。
<IfModule mpm_prefork_module>
StartServers 5 # 启动时的进程数
MinSpareServers 5 # 最小空闲进程数
MaxSpareServers 10 # 最大空闲进程数
MaxRequestWorkers 150 # 最大并发请求数(根据内存调整,每进程约消耗10-20MB)
MaxConnectionsPerChild 1000 # 每个进程处理请求上限(防止内存泄漏)
</IfModule>
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 256
MaxConnectionsPerChild 0
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 30 days"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType application/javascript "access plus 30 days"
</IfModule>
这会让浏览器缓存这些资源,降低服务器负载。<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
支持gzip压缩,提升页面加载速度。/etc/sysctl.conf优化网络性能,关键参数如下:net.ipv4.tcp_fin_timeout = 30 # TIME_WAIT状态超时时间(秒)
net.ipv4.tcp_tw_reuse = 1 # 允许复用TIME_WAIT套接字
net.ipv4.tcp_max_syn_backlog = 8192 # SYN队列长度(应对高并发连接请求)
net.ipv4.ip_local_port_range = 1024 65000 # 客户端可用端口范围
net.core.somaxconn = 65535 # 监听队列最大长度
执行sysctl -p使配置生效。LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheRoot "/var/cache/apache2/mod_cache_disk" # 缓存目录
CacheEnable disk / # 对根路径启用磁盘缓存
CacheDirLevels 2 # 缓存目录层级
CacheDirLength 1 # 目录名长度
</IfModule>
</IfModule>
创建缓存目录并授权:mkdir -p /var/cache/apache2/mod_cache_disk && chown apache:apache /var/cache/apache2/mod_cache_disk。CustomLog logs/access_log common(使用简洁格式)、LogLevel warn(仅记录警告及以上级别日志)。mod_cgi、mod_status),减少内存消耗。编辑httpd.conf,注释对应行:# LoadModule cgi_module modules/mod_cgi.so。/etc/security/limits.conf,增加系统可打开文件数:* soft nofile 65535
* hard nofile 65535
临时生效:ulimit -n 65535。