跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

如何解决Ubuntu系统中nginx部署PHP项目时所有请求返回404错误的问题?

在Ubuntu系统中使用Nginx部署PHP项目时,经常会遇到所有请求都返回404错误的情况。这通常是由于Nginx配置文件配置错误导致的。本文将详细讲解如何正确配置Nginx,确保你的PHP项目能够在8088端口正常运行。 一位用户在部署PHP项目时,遇到了所有接口返回404的难题。以下是他的Nginx配置文件:
server { listen 8088; server_name localhost; root /var/www/html; location / { index index.php index.html index.htm; try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; fastcgi_index index.php; fastcgi_param script_filename $document_root$fastcgi_script_name; include fastcgi_params; } }
问题出在
location ~ \.php$
块中的
try_files
指令。正确的配置如下:
server { listen 8088; server_name localhost; root /var/www/html; location / { index index.php index.html index.htm; try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { # try_files $uri =404; 删除错误的try_files指令 fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; # 关键修改 fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param PATH_INFO $fastcgi_path_info; } }
关键在于添加了
fastcgi_split_path_info
fastcgi_param PATH_INFO
指令。这两条指令对于处理PHP的URL重写至关重要,尤其是在使用ThinkPHP 6 (TP6)等框架时。 如果使用TP6,可以搜索“TP6 Nginx fastcgi”获取更多配置示例。 同时,请注意将
script_filename
参数中的
script_filename
改为
SCRIPT_FILENAME
(大小写敏感)。 Nginx 在宝塔面板中轻松管理Nginx高性能Web服务器。提供可视化配置反向代理、负载均衡、SSL证书及HTTP缓存功能,一键优化高并发性能,助您高效搭建稳定、快速的网站运行环境。 下载 立即学习 “ PHP免费学习笔记(深入) ”; 另外,请确保php-fpm服务正在运行,并且
/var/run/php/php7.4-fpm.sock
路径正确。 如果使用其他版本的PHP,请相应调整sock文件的路径。 通过以上配置和检查,你的PHP项目应该能够在8088端口正常访问。

相关文章