Nginx 404 page implementation of several ways of three

  • 2020-05-15 03:30:24
  • OfStack

A website project, certainly can't avoid 404 page, usually use Nginx as Web server, there are the following centralized configuration, 1 to look at.

Type 1: Nginx's own error page

Nginx accesses a static html page. When the page is not available, Nginx throws a 404. How do you return it to the client?

If you look at the configuration below, you can do this without changing any of the parameters.


server {
listen  80;
server_name www.test.com;
root /var/www/test;
index index.html index.htm;
location / {
}
#  Define the error page code, and if the corresponding error page code appears, forward it there. 
error_page 404 403 500 502 503 504 /404.html;
#  Take the top location . 
location = /404.html {
#  Directory path to put the error page. 
root /usr/share/nginx/html;
}
}

Type 2: reverse proxy error pages

If the background Tomcat handling error is thrown 404, and you want to feedback the state to the client by calling Nginx or redirect to a connection, the configuration is as follows:


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;
}
#  Key parameter: after this variable is turned on, we can customize the error page when the back end returns 404 . nginx Intercept error definition error page 
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;
}
}

Type 3: Nginx parses the error pages of php code

If the back end is php parsed, you need to add 1 variable

Add a variable fastcgi_intercept_errors on to the http segment.

Specify 1 error page:


error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}

Specify 1 url address:

error_page 404 /404.html;

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

conclusion


Related articles: