在CentOS上搭建Web服务器(如Apache/Nginx)时,即使是有经验的工程师也可能遇到一些隐蔽的陷阱。以下是常见的10个关键问题及对应的专业解决方案:
SELinux导致的权限拒绝
bash
# 临时设置
setenforce 0
# 永久关闭(不推荐)
sed -i 's/SELINUX=enforcing/SELINUX=permissive/g' /etc/selinux/config
# 推荐方案:调整上下文
chcon -R -t httpd_sys_content_t /var/www/html
Firewalld未正确配置
bash
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
PHP-FPM进程崩溃
ini
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 3
pm.max_spare_servers = 10
虚拟主机配置错误
nginx
server {
listen 80;
server_name example.com; # 必须与域名完全匹配
root /var/www/example; # 结尾不要加斜杠
index index.php index.html;
}
文件系统选择不当
bash
# 推荐使用XFS并禁用atime
mount -o noatime,nodiratime /dev/sdb1 /var/www
日志文件膨胀
conf
/var/log/nginx/*log {
daily
rotate 30
missingok
compress
delaycompress
notifempty
sharedscripts
postrotate
/bin/kill -USR1 $(cat /run/nginx.pid 2>/dev/null) 2>/dev/null || true
endscript
}
SSL/TLS配置不安全
nginx
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:ECDHE-ECDSA-AES128-GCM-SHA256';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
未启用HTTP/2
nginx
listen 443 ssl http2; # 注意:必须先启用SSL
数据库连接限制
ini
[mysqld]
max_connections = 200
wait_timeout = 30
未配置自动化监控
bash
# 系统监控
yum install -y netdata
# Web服务器状态
nginx-module-vts # 对于Nginx
mod_status # 对于Apache
高级建议:
1. 使用配置管理工具(如Ansible)保持环境一致性:
yaml
- name: Ensure web packages are installed
yum:
name: ["nginx", "php-fpm"]
state: latest
对于生产环境,建议采用以下架构:
Load Balancer (HAProxy) → Web Servers → Database (Master-Slave)
↑
CDN Cache
性能测试必备工具:
# 压力测试
ab -n 10000 -c 500 http://example.com/
# 实时监控
dstat -tcmnd --disk-util
遇到具体问题时,建议按以下流程排查:
1. 检查错误日志:journalctl -xe
和 tail -f /var/log/nginx/error.log
2. 验证配置语法:nginx -t
或 apachectl configtest
3. 网络连通性测试:curl -vI http://localhost
4. 进程状态检查:systemctl status nginx -l
记住:生产环境每次修改前应创建备份快照,并使用strace
和tcpdump
进行深度诊断当常规方法失效时。