66

Nginx设置404页面

 5 years ago
source link: https://www.linuxprobe.com/nginx-setting-404.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
导读 Nginx是俄罗斯人编写的十分轻量级的HTTP服务器,是一个高性能的HTTP和反向代理服务器,同时也是一个IMAP/POP3/SMTP 代理服务器。一个网站项目,肯定是避免不了404页面的,通常使用Nginx作为Web服务器时,有以下集中配置方式,一起来看看。
第一种:Nginx自己的错误页面

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;

}

}
第二种:反向代理的错误页面

如果后台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;

}

}
第三种:Nginx解析php代码的错误页面

如果后端是php解析的,需要加一个变量

在http段中加一个变量 fastcgi_intercept_errors on 就可以了。

指定一个错误页面:

error_page    404  /404.html;

location = /404.html {

root   /usr/share/nginx/html;

}

指定一个url地址:

error_page 404  /404.html;

error_page 404 = http://www.test.com/error.html;

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK