nginx请求PHP文件404,nginx+php设置自定义404页面

运行环境为nginx+php时,当web服务器找不到文件的时候会报出404的错误。如果不想让用户看到系统的错误提示,设置自定义的页面,可以增加安全性和友好度体验。

配置nginx的自定义404页面,需要在nginx.conf配置两个地方。

一个是nginx报出的404错误,当一些前端的静态文件如html文件、css文件等,直接是nginx去查找文件,如果没有这个文件nginx会报出404 Not Found nginx的错误。

一个是php报出的404错误,当一些脚本文件,比如php动态文件,nginx需要调用php-fpm去解析,nginx本身不能解析这些文件,所以当php解析时找不到这个php文件时,php也会返回404错误,并报错为File not found.

自定义404页面的两处nginx.conf配置文件代码配置:

server {

listen 80;

#多域名用空格隔开

server_name zixuephp.net m.zixuephp.net;

#设置默认访问首页

index index.php index.html;

#默认编码

charset utf-8;

#设置404或其他错误跳转到指定的页面

error_page 500 502 503 504 404 /404.html;

#nginx解析php脚本

location ~ .php$ {

#设置php返回404屏蔽 File not found. 错误设置

try_files $uri =404;

root html;

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;

include fastcgi_params;

index index.php index.html;

}

}

在nginx.conf配置error_page 500 502 503 504 404 /404.html; 和 try_files $uri =404;代码即可。

运行环境为nginx+php时,当web服务器找不到文件的时候会报出404的错误。如果不想让用户看到系统的错误提示,设置自定义的页面,可以增加安全性和友好度体验。 配置nginx的自定义404页面,需要在nginx.conf配置两个地方。 一个是nginx报出的404错误,当一些前端的静态文件如html文件、css文件等,直接是nginx去查找文件,如果没有这个文件nginx会报出404 Not Found nginx的错误。 一个是php报出的404错误,当一些脚本文件,比如php动态文件,nginx需要调用php-fpm去解析,nginx本身不能解析这些文件,所以当php解析时找不到这个php文件时,php也会返回404错误,并报错为File not found. 自定义404页面的两处nginx.conf配置文件代码配置: server { listen 80; #多域名用空格隔开 server_name zixuephp.net m.zixuephp.net; #设置默认访问首页 index index.php index.html; #默认编码 charset utf-8; #设置404或其他错误跳转到指定的页面 error_page 500 502 503 504 404 /404.html; #nginx解析php脚本 location ~ .php$ { #设置php返回404屏蔽 File not found. 错误设置 try_files $uri =404; root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name; include fastcgi_params; index index.php index.html; } } 在nginx.conf配置error_page 500 502 503 504 404 /404.html; 和 try_files $uri =404;代码即可。
经验分享 程序员 微信小程序 职场和发展