Nginx配置示例:
server {
# 静态资源缓存设置
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg|eot)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
access_log off;
log_not_found off;
}
# 静态文件服务
location /static/ {
alias /path/to/static/files/;
try_files $uri =404;
}
}
Apache配置示例:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType application/x-javascript "access plus 1 year"
</IfModule>
Nginx配置:
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_proxied any;
gzip_vary on;
推荐方案: - Cloudflare - AWS CloudFront - 阿里云CDN - 腾讯云CDN
# 安装Redis
sudo yum install epel-release
sudo yum install redis
sudo systemctl start redis
sudo systemctl enable redis
PHP连接Redis示例:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->set('cache_key', 'cached_data', 3600); // 缓存1小时
MySQL查询缓存配置:
-- 检查查询缓存状态
SHOW VARIABLES LIKE 'query_cache%';
-- 启用查询缓存 (my.cnf中配置)
query_cache_type = 1
query_cache_size = 64M
query_cache_limit = 2M
# 安装OPcache
sudo yum install php-opcache
# 配置OPcache (/etc/php.d/opcache.ini)
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
# 编辑/etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
fs.file-max = 65535
# 应用配置
sudo sysctl -p
Nginx worker配置:
worker_processes auto; # 自动根据CPU核心数设置
worker_rlimit_nofile 65535;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
# 安装htop
sudo yum install htop
# 安装nginx-status模块
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
# 安装GoAccess日志分析工具
sudo yum install goaccess
# 分析Nginx日志
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --log-format=COMBINED
# 允许HTTP/HTTPS
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
通过以上优化措施,您的CentOS Web服务器将能够更高效地处理静态和动态内容,显著提升网站性能和用户体验。