A website project can't avoid 404 pages. When using Nginx as a Web server, there are the following centralized configurations:
First: Nginx's own error page
Nginx accesses a static html page. When the page does not exist, nginx throws 404, so how to return it to the client 404?
Look at the following configuration. In this case, you can implement this function without modifying any parameters.
server {
listen 80;
server_name www.test.com;
root /var/www/test;
index index.html index.htm;
location / {
}
# Define the error page code. If there is a corresponding error page code, forward it there.
error_page 404 403 500 502 503 504 /404.html;
# Take the location above.
location = /404.html {
# The directory path where the error page is placed.
root /usr/share/nginx/html;
}
}
Second: error page of reverse proxy
If the background Tomcat processing reports an error and throws 404, you want to feedback the status as Nginx to the client 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 enabled, we can customize the error page. When the backend returns 404, nginx intercepts the 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;
}
}
The third kind: Nginx parses the error page of php code
If the backend is parsed by php, you need to add a variable
Add a variable fastcgi ﹣ intercept ﹣ errors on ﹣ to the http segment.
-
Specify an error page:
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
-
Specify a url address:
error_page 404 /404.html;
error_page 404 = http://www.test.com/error.html;