在CentOS上优化Apache HTTP服务器的性能是一个多方面的过程,涉及配置调整、资源管理和网络优化等。以下是一些基本的优化步骤和建议:
启用KeepAlive:
在Apache配置文件(通常是/etc/httpd/conf/httpd.conf
)中添加以下行来启用KeepAlive:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
这将设置最大KeepAlive请求数为100,并将超时时间设置为5秒。
调整MPM(多处理模块)设置:
根据服务器硬件资源和负载情况,调整MPM设置可以提高并发处理能力。例如,对于CentOS 7的Apache,默认使用的MPM是prefork
。可以编辑Apache配置文件中的MPM配置:
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
ServerLimit 256
MaxClients 256
MaxRequestsPerChild 0
</IfModule>
这些值需要根据实际情况进行调整。
启用静态文件缓存:
使用mod_expires
模块来实现静态文件缓存。在Apache配置文件中添加以下行:
<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>
这将为不同类型的文件设置缓存时间。
使用压缩技术: 启用Gzip压缩可以减小传输的数据量,提高网站加载速度。在Apache配置文件中添加以下行来启用Gzip压缩:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
这将对指定类型的文件进行gzip压缩。
启用HTTP/2协议:
通过启用HTTP/2协议来提高服务器性能。可以使用mod_http2
模块来实现HTTP/2支持。在Apache配置文件中添加以下行:
LoadModule http2_module modules/mod_http2.so
然后重启Apache服务。
使用缓存代理:
通过启用缓存代理来减少对后端服务器的请求次数,从而提高服务器性能。可以使用mod_proxy
和mod_cache
模块来实现缓存代理。
网络优化:
调整内核参数以优化网络性能。例如,编辑/etc/sysctl.conf
文件,增加以下几行:
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
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
然后执行以下命令使内核配置立马生效:
sudo sysctl -p
这些参数可以帮助减少TIME_WAIT套接字数量,提高网络性能。
关闭不必要的模块:
在编译安装Apache时,禁用不需要的模块可以减少服务器的攻击面。例如,在./configure
命令中添加:
--disable-ssl --disable-cgi --disable-mod_ssl
然后重新编译并安装Apache。
配置防火墙:
使用iptables
或firewalld
设置合适的防火墙规则,仅允许必要的端口开放。例如,使用firewalld
:
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
这可以确保Apache服务器的安全性。
通过上述优化策略,可以显著提高CentOS上Apache服务器的性能和安全性。在进行任何配置更改后,请确保重启Apache服务以使更改生效。