温馨提示×

CentOS Apache配置优化技巧有哪些

小樊
63
2025-03-31 18:00:37
栏目: 智能运维

在CentOS上配置和优化Apache服务器是一个涉及多个方面的过程,旨在提高服务器的性能、安全性和稳定性。以下是一些关键的优化技巧和步骤:

基本配置

  1. 安装Apache
  • 确保系统是最新的,然后使用yum安装Apache:
    sudo yum update -y
    sudo yum install httpd -y
    
  1. 启动并启用Apache服务
  • 启动Apache并设置开机自启:
    sudo systemctl start httpd
    sudo systemctl enable httpd
    
  1. 配置防火墙
  • 开放HTTP(端口80)和HTTPS(端口443):
    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    sudo firewall-cmd --reload
    
  1. 配置虚拟主机
  • 创建网站根目录和文件,并在配置文件中设置DocumentRoot和ServerName。

性能优化

  1. 启用KeepAlive
  • httpd.conf中添加以下行来启用KeepAlive:
    KeepAlive On
    MaxKeepAliveRequests 100
    KeepAliveTimeout 5
    
  1. 调整MPM(多处理模块)设置
  • 根据服务器硬件资源和负载情况,调整MPM设置。例如,使用prefork模块:
    <IfModule mpm_prefork_module>
        StartServers 5
        MinSpareServers 5
        MaxSpareServers 10
        MaxRequestWorkers 150
        MaxConnectionsPerChild 0
    </IfModule>
    
  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 image/gif "access plus 1 year"
        ExpiresByType application/javascript "access plus 30 days"
    </IfModule>
    
  1. 使用压缩技术
  • 启用Gzip压缩以减少传输数据量:
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
    </IfModule>
    
  1. 优化内核参数
  • 编辑/etc/sysctl.conf文件,调整TCP连接数、文件句柄数等参数:
    net.ipv4.tcp_tw_reuse = 1
    net.ipv4.tcp_tw_recycle = 1
    net.ipv4.ip_local_port_range = 1024 65000
    net.ipv4.tcp_max_syn_backlog = 8192
    net.ipv4.tcp_max_tw_buckets = 5000
    
  1. 启用SSL/TLS
  • 使用Certbot生成并安装SSL证书,启用HTTPS:
    sudo yum install epel-release -y
    sudo yum install certbot python2-certbot-apache -y
    sudo certbot --apache -d yourdomain.com -d www.yourdomain.com
    

安全性优化

  1. 配置防火墙规则
  • 仅允许必要的端口开放,如80(HTTP)和443(HTTPS)。
  1. 限制访问权限
  • 使用身份验证和授权机制限制对Apache服务器的访问。
  1. 隐藏版本信息
  • httpd.conf中修改ServerTokensServerSignature指令以隐藏版本信息。

监控和维护

  1. 使用监控工具
  • 安装并使用sysstat、sar、top等工具监控系统性能。
  1. 定期更新和维护
  • 定期检查并更新Apache及其相关组件的版本,以修复已知的安全漏洞。

通过上述优化技巧,可以显著提高CentOS上Apache服务器的性能和安全性。在进行任何配置更改后,请确保重新启动Apache服务以使更改生效。

0