一、概述
很多时候我们访问一个网站,例如360,或者腾讯的页面,当该页面不存在的时候,会提示404未找到,然后右下角会出现 爱心帮助的 图片等,然后这些图片或者问题都是随机的,也许你下次访问的时候就是另外的页面了。现在我们通过nginx结合php来实现这么个需求。
二、配置
前提: LEMP环境(略)
①编辑nginx配置文件(/etc/nginx/nginx.conf)location / {
###
if (!-e $request_filename) {
rewrite ^(.*)$ /error/404.php redirect;
}
####请求的时候判断请求的文件是否存在,不存在则显示重写到/error/ ##404.php页面去
root /webdoc/;
index index.php index.html index.htm;
}
location ~ \.php$ {
##________________________________##这里是当请求的.php页面不存在的时候也 # 重写到/error/404.php页面,如果不存在行 # ,则请求的php页面不会404错误
if (!-e $request_filename) {
rewrite ^(.*)$ /error/404.php redirect;
}
############################
root /webdoc/;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
②编辑/error/404.php页面<?php
$num=mt_rand(1,9); ##从1-9当中随机生成数字
echo $num;
echo ""; ##显示目录下的对应数字的图片
?>
③添加本地图片
④测试
首页正常显示:
输入不存在的url时候效果:
回车后:
达到效果~~