SoFunction
Updated on 2025-03-02

Two ways to implement the configuration method of 404 pages in Nginx

A website project will definitely not avoid 404 pages. Usually when using Nginx as a web server, there are the following centralized configuration methods. Let’s take a look.

The first type: Nginx's own error page

  • Nginx accesses a static html page. When this page does not exist, Nginx throws 404. So how to return it to the client 404?
  • Look at the configuration below. In this case, this function can be implemented without modifying any parameters.
    server {
        listen      80;
        server_name  ;
        root   /html;
        index   ;
        location / {

        }
    }

Define the error page code. If the corresponding error page code appears, forward it to it.

error_page  404 403 500 502 503 504  /;

Accept the above location.

location = / {

Place the directory path to the error page.

root   /usr/share/nginx/html;

The second type: the error page of the reverse proxy

If the background Tomcat reports an error and throws a 404, and wants to call this state Nginx to feed back to the client or redirect it to a certain 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 ;
        root   /html;
        index   ;
        location / {
        	if ($request_uri ~* ‘^/$') {
        		rewrite .*   / redirect
    		}
    	}
    }

Key parameters: After this variable is turned on, we can customize the error page. When the backend returns 404, nginx intercepts the 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  /;
    location = / {
    	root   /usr/share/nginx/html;
    }

Specify a URL address:

    error_page 404  /;
    error_page 404 = /;

This is the end of this article about the two methods of Nginx implementing the configuration method of 404 page. For more information about Nginx 404 page configuration content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!