第一种情况:处理nginx自己产生的404状态
nginx访问一个静态的html 页面,当这个页面没有的时候,Nginx抛出404,通过下面配置可以指定一个404页面返回给客户端:
server {
listen 80;
server_name www.test.com;
root /var/www/test;
index index.html index.htm;
location / {
}
# 定义错误页面码,如果出现相应的错误页面码,转发到那里。
error_page 404 403 500 502 503 504 /404.html;
# 承接上面的location。
location = /404.html {
# 放错误页面的目录路径。
root /usr/share/nginx/html;
}
}
第二种:处理反向代理的产生的404状态码
比如tomcat处理报错抛出404,想把这个状态叫Nginx反馈给客户端或者重定向到某个连接,配置如下:
upstream www {
server 192.168.1.201:7777 weight=20 max_fails=2 fail_timeout=30s;
ip_hash;
}
server {
listen 80;
server_name www.test.com;
root /var/www/test;
index index.html index.htm;
location / {
if ($request_uri ~* ‘^/$’) {
rewrite .* http://www.test.com/index.html redirect;
}
#关键参数:这个变量开启后,我们才能自定义错误页面,当后端返回404
#nginx拦截错误定义错误页面
proxy_intercept_errors on;
proxy_pass http://www;
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-FOR $proxy_add_x_forwarded_for;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
}
第三种:php代码的产生的404错误代码
和反向代理类似,但需要使用 fastcgi_intercept_errors on 配置来拦截错误。比如:
server {
listen 80;
server_name 360kb.com;
location / {
index index.html index.htm;
if ($request_filename !~ (assets|admin|doc|robots\.txt|.*\.html|.*\.php) ) {
rewrite ^/(.*)$ /index.php?_url=/$1 last;
break;
}
}
location ~ \.php$ {
fastcgi_intercept_errors on
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
}
还可以直接指定一个URL来响应404.
error_page 404 = http://www.360kb.com/404.html;