温馨提示×

CentOS Apache如何优化网络

小樊
47
2025-11-01 14:56:54
栏目: 智能运维

一、内核参数优化(系统级网络性能提升)
通过调整内核参数,可减少TCP连接开销、提升网络吞吐能力。编辑/etc/sysctl.conf文件,添加/修改以下关键参数:

  • net.ipv4.tcp_fin_timeout = 30:缩短TIME_WAIT状态的超时时间(默认60秒),加速端口释放;
  • net.ipv4.tcp_tw_reuse = 1:允许复用TIME-WAIT状态的socket,提升并发连接效率;
  • net.ipv4.tcp_max_syn_backlog = 8192:增加SYN队列长度,应对高并发连接请求;
  • net.ipv4.tcp_keepalive_time = 1200:延长keepalive探测间隔(默认7200秒),减少无效探测;
  • net.ipv4.ip_local_port_range = 10000 65000:扩大本地端口范围,支持更多并发外网连接。
    执行sudo sysctl -p使配置立即生效。

二、Apache配置文件核心参数调优

  1. KeepAlive优化:启用持久连接以减少TCP握手开销,在httpd.conf中设置:
    KeepAlive On
    MaxKeepAliveRequests 100  # 单个连接最大请求数(避免单个连接占用过久)
    KeepAliveTimeout 5        # 连接保持时间(秒,平衡响应速度与资源占用)
    
  2. MPM(多处理模块)调整:根据服务器硬件选择合适的工作模式(CentOS 7+默认用event,高并发场景推荐):
    • event模式(适用于异步非阻塞IO,推荐):
      <IfModule mpm_event_module>
          StartServers 5          # 启动时的子进程数
          MinSpareThreads 25      # 最小空闲线程数
          MaxSpareThreads 75      # 最大空闲线程数
          MaxRequestWorkers 768   # 最大并发请求数(根据内存调整,每进程约消耗5-10MB)
          MaxConnectionsPerChild 1000  # 每个子进程处理的最大请求数(防止内存泄漏)
      </IfModule>
      
    • prefork模式(适用于兼容性场景,如旧版CGI应用):
      <IfModule mpm_prefork_module>
          StartServers 5
          MinSpareServers 5
          MaxSpareServers 10
          MaxRequestWorkers 256   # prefork模式下需更低,避免内存耗尽
          MaxConnectionsPerChild 0
      </IfModule>
      
  3. 超时设置:缩短Timeout参数(默认120秒),降低长连接对资源的占用:
    Timeout 30  # 建议30秒内无响应则断开连接
    

三、静态资源缓存与压缩

  1. 静态文件缓存:通过mod_expires模块设置缓存时间,减少重复请求。在配置文件中添加:
    <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>
    
  2. Gzip压缩:使用mod_deflate模块压缩HTML、CSS、JS等文本资源,减少传输体积。配置示例如下:
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
    </IfModule>
    

四、启用HTTP/2协议
HTTP/2支持多路复用、头部压缩等功能,能显著提升页面加载速度。需启用mod_http2模块:

LoadModule http2_module modules/mod_http2.so
Protocols h2 http/1.1  # 在VirtualHost或全局配置中添加,优先使用HTTP/2

重启Apache后生效:sudo systemctl restart httpd

五、禁用不必要的模块与服务

  1. 禁用无用模块:通过a2dismod命令(CentOS 7+)或注释httpd.conf中的LoadModule行,禁用不需要的模块(如cgissl若未使用):
    sudo a2dismod cgi status autoindex  # 示例:禁用cgi、status、autoindex模块
    sudo systemctl restart httpd
    
  2. 关闭不必要的服务:停止并禁用与Apache无关的服务(如telnetftp),减少系统资源消耗。

六、网络层安全与访问控制

  1. 防火墙配置:使用firewalld仅开放必要端口(HTTP 80、HTTPS 443),阻止非法访问:
    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    sudo firewall-cmd --reload
    
  2. 隐藏版本信息:在httpd.conf中设置,避免暴露Apache版本给攻击者:
    ServerSignature Off  # 关闭错误页面中的服务器版本信息
    ServerTokens Prod    # 仅显示“Apache”而非详细版本
    

0