错误表现:修改Nginx配置文件(如/etc/nginx/nginx.conf
或/etc/nginx/conf.d/*.conf
)后,重启服务时报错“configuration file /etc/nginx/nginx.conf test failed”或类似提示。
解决方法:
nginx -t
命令测试配置文件语法,命令会明确提示错误位置(如行号、未知指令);unknowndirective
)、缺失的分号或括号;include
指令引用的文件路径存在(如include /etc/nginx/conf.d/*.conf;
)。错误表现:启动或重启Nginx时报错“bind() to 0.0.0.0:80 failed (98: Address already in use)”或“Address already in use”。
解决方法:
netstat -tulnp | grep :80
(或目标端口)命令查找占用端口的进程;kill -9 <PID>
(替换为实际进程ID);listen
指令(如改为listen 8080;
),或停止占用服务(如systemctl stop httpd
)。错误表现:
nginx
或www-data
)对相关目录/文件有读写权限:chown -R nginx:nginx /var/log/nginx/ # 日志目录
chown -R nginx:nginx /usr/share/nginx/html/ # 静态资源目录
chmod -R 755 /var/log/nginx/ /usr/share/nginx/html/ # 设置合理权限
chcon -R -t httpd_sys_rw_content_t /var/log/nginx/
。错误表现:浏览器访问网站时显示“502 Bad Gateway”,Nginx错误日志中显示“upstream prematurely closed connection”或“no live upstreams”。
解决方法:
systemctl status php-fpm
(以PHP-FPM为例);proxy_pass
或fastcgi_pass
指令指向正确的后端地址(如fastcgi_pass unix:/run/php/php-fpm.sock;
);location ~ \.php$ {
proxy_connect_timeout 60s; # 连接超时时间
proxy_send_timeout 60s; # 发送超时时间
proxy_read_timeout 60s; # 接收超时时间
fastcgi_pass unix:/run/php/php-fpm.sock;
}
firewall-cmd --add-port=9000/tcp --permanent # 开放后端端口(如PHP-FPM的9000端口)
firewall-cmd --reload
setsebool -P httpd_can_network_connect 1 # 允许HTTP服务连接网络
错误表现:访问不存在的页面或静态资源时显示“404 Not Found”,Nginx错误日志中显示“open() “/path/to/file” failed (2: No such file or directory)”。
解决方法:
root
或alias
指令是否指向正确的资源目录(如root /var/www/html;
);/var/www/html/index.html
);server
块中添加配置:error_page 404 /custom_404.html;
location = /custom_404.html {
root /usr/share/nginx/html;
internal;
}
并创建/usr/share/nginx/html/custom_404.html
文件(内容自定义)。错误表现:访问网站时显示“403 Forbidden”,Nginx错误日志中显示“open() “/path/to/file” failed (13: Permission denied)”或“directory index of “/path/” is forbidden”。
解决方法:
nginx
)有读取权限,目录权限建议设为755
,文件权限设为644
;index.html
或index.php
等默认首页,需启用目录索引或添加默认首页:location / {
autoindex on; # 开启目录索引(可选,仅用于调试)
index index.html index.php; # 指定默认首页
}
disable_symlinks off;
指令(默认开启,会阻止访问符号链接)。错误表现:访问HTTPS网站时报错“SSL_CTX_use_PrivateKey_file failed”或“certificate routines:X509_check_private_key:key values mismatch”,或浏览器提示“证书无效”。
解决方法:
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
);openssl x509 -noout -modulus -in fullchain.pem | openssl md5
和openssl rsa -noout -modulus -in privkey.pem | openssl md5
命令,比较两者的MD5值是否一致;certbot --nginx -d example.com -d www.example.com
。错误表现:无法快速定位问题根源,或错误反复出现。
解决方法:
/var/log/nginx/error.log
,访问日志位于/var/log/nginx/access.log
;tail -f /var/log/nginx/error.log
实时查看错误日志,或tail -n 50 /var/log/nginx/error.log
查看最近50条错误;grep
命令过滤关键错误(如grep "502" /var/log/nginx/error.log
)。