search
HomeOperation and MaintenanceNginxHow to configure the 404 page in Nginx and the AJAX request to return the 404 page

404 page basic configuration
404 error is an error that easily occurs when accessing www websites. The most common error message: 404 not found. The settings of the 404 error page have a great impact on the SEO of the website. Improper settings, such as direct redirection to the homepage, etc., will be demoted and plucked by search engines. The purpose of the 404 page should be to tell the user that the page you requested does not exist, and to guide the user to browse other pages of the website instead of closing the window and leaving. Search engines use http status codes to identify the status of web pages. When a search engine obtains a bad link, the website should return a 404 status code to tell the search engine to abandon indexing the link. If a 200 or 302 status code is returned, the search engine will index the link, resulting in a large number of different links pointing to the same web page content. As a result, search engines’ trust in the website has been significantly reduced.
The following is a tutorial for lnmp to set up nginx 404 error page:
1,

vi /usr/local/nginx/conf/nginx.conf

Edit the nginx configuration file and add the following code in the http section:

fastcgi_intercept_errors on;

How to configure the 404 page in Nginx and the AJAX request to return the 404 page

2. Edit the website configuration file, for example this site:

vi /usr/local/nginx/conf/vhost/onelone.com.conf

, add the following code in the server section:

error_page 404 = /404.html;

Note: Some netizens tested the uplink The code needs to remove the equal sign to return the correct 404 status, so students are asked to test whether they want to remove the equal sign.

How to configure the 404 page in Nginx and the AJAX request to return the 404 page

3. Test whether the configuration file is correct:

/usr/local/nginx/sbin/nginx -t

, return the following code to pass:

the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
configuration file /usr/local/nginx/conf/nginx.conf test is successful

4 , restart lnmp to take effect: /root/lnmp restart.

How to configure the 404 page in Nginx and the AJAX request to return the 404 page

5. Notes on creating 404 error pages:
(1) Do not redirect 404 errors to the homepage of the website, otherwise it may cause the homepage to be lost in search The engine is downgraded or disappears.
(2) Do not use absolute URLs. If you use absolute URLs, the status code returned is 302 200, which will generate a large number of duplicate web pages.
(3) The 404 page setting is completed, be sure to check whether it is correct. The http header information returned must be a 404 status. This can be checked through the server header information inspection tool.
(4) Do not automatically jump to the 404 page, let the user decide where to go.
The custom 404 page must be larger than 512 bytes, otherwise the ie default 404 page may appear.

The 404 page requested by ajax returns
A few days ago, a friend had a problem with his program but couldn't find the problem no matter how much he checked, so he asked me to help him check it out. In fact, it is ajax requesting many templates, and then writing the templates to the page. The key is that all requested pages return a 200 normal status code. On the surface, there is no problem. In fact, although some requests return a 200 status code, the status code returned is 200. The webserver is nginx and directly told me that they should have configured nginx's 404 error page. Although the request for non-existent resources can successfully return a 404 page, the return status code is indeed 200.

404.html
this is 404 page.

Request a page that does not exist:

How to configure the 404 page in Nginx and the AJAX request to return the 404 page

ajax code:

$.ajax({
 url: "does_not_exist.html",
 success : function(response, textstatus){
 console.log(textstatus+":"+response);
 },
 error : function(xmlhttprequest, textstatus, errorthrown){
 console.log([xmlhttprequest, textstatus, errorthrown].join(","));
 }
});

Execution result :

How to configure the 404 page in Nginx and the AJAX request to return the 404 page

Enter object to see details:

How to configure the 404 page in Nginx and the AJAX request to return the 404 page

The requested page cannot be found and The 404 page information is returned, but the status code is still 200, so jquery does not use the error function callback but directly uses the success callback.
There should be a problem with the configuration, so I opened nginx.conf and found that their configuration was written like this:

error_page 404 = /404.html;

So I checked the official website document and rewritten the above expression as:

error_page 404 /404.html;

Then restart

d:\nginx-1.5.11>nginx.exe -s reload

Try again:

How to configure the 404 page in Nginx and the AJAX request to return the 404 page

Let’s take a look at the ajax request:

How to configure the 404 page in Nginx and the AJAX request to return the 404 page

It is obvious that compared with the previous one that returns a red 404 status code, what comes out of the console.log below is

[object object],error,not found

and then click Enter object to see:

How to configure the 404 page in Nginx and the AJAX request to return the 404 page

status value is 404. It can not only return the 404 page, but also return the 404 status code so that the ajax request can judge the page request status based on the status code and handle the error.

The following are the additions from other netizens:

1. The reason why nginx error page is displayed elegantly?
When we visit the website, due to special reasons, errors such as 403, 404, 503 often appear, which greatly affects the user's access experience, so it is necessary for us to make an elegant display of the error page to improve the user's browsing experience.

2. How to define elegantly displayed pages under nginx?
Let’s take the 404 error as an example. The specific steps are as follows:
1. Create your own 404.html page and place it under the site directory;
2. Change the nginx.conf configuration file and set it in the http module Add fastcgi_intercept_errors on;
3. Change the nginx.conf configuration file and add: error_page 404 /404.html; or error_page 404 =http://www.hulala.com/404.html;
4. Check the syntax /nginx/sbin/nginx -t after the change, and restart nginx;
Now, the elegant display of the 404 error page has been configured ok.

Draw inferences from one example: 502, 403 and other errors can be configured in the same way.
error_page 500 502 503 504 /50x.html;
error_page 403 /403.html;
Note:
The two prerequisites for error redirection to take effect in nginx are: fastcgi_intercept_errors on, And the error_page option is set correctly.

The above is the detailed content of How to configure the 404 page in Nginx and the AJAX request to return the 404 page. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Using NGINX: Optimizing Website Performance and ReliabilityUsing NGINX: Optimizing Website Performance and ReliabilityMay 09, 2025 am 12:19 AM

NGINX can improve website performance and reliability by: 1. Process static content as a web server; 2. forward requests as a reverse proxy server; 3. allocate requests as a load balancer; 4. Reduce backend pressure as a cache server. NGINX can significantly improve website performance through configuration optimizations such as enabling Gzip compression and adjusting connection pooling.

NGINX's Purpose: Serving Web Content and MoreNGINX's Purpose: Serving Web Content and MoreMay 08, 2025 am 12:07 AM

NGINXserveswebcontentandactsasareverseproxy,loadbalancer,andmore.1)ItefficientlyservesstaticcontentlikeHTMLandimages.2)Itfunctionsasareverseproxyandloadbalancer,distributingtrafficacrossservers.3)NGINXenhancesperformancethroughcaching.4)Itofferssecur

NGINX Unit: Streamlining Application DeploymentNGINX Unit: Streamlining Application DeploymentMay 07, 2025 am 12:08 AM

NGINXUnit simplifies application deployment with dynamic configuration and multilingual support. 1) Dynamic configuration can be modified without restarting the server. 2) Supports multiple programming languages, such as Python, PHP, and Java. 3) Adopt asynchronous non-blocking I/O model to improve high concurrency processing performance.

NGINX's Impact: Web Servers and BeyondNGINX's Impact: Web Servers and BeyondMay 06, 2025 am 12:05 AM

NGINX initially solved the C10K problem and has now developed into an all-rounder who handles load balancing, reverse proxying and API gateways. 1) It is well-known for event-driven and non-blocking architectures and is suitable for high concurrency. 2) NGINX can be used as an HTTP and reverse proxy server, supporting IMAP/POP3. 3) Its working principle is based on event-driven and asynchronous I/O models, improving performance. 4) Basic usage includes configuring virtual hosts and load balancing, and advanced usage involves complex load balancing and caching strategies. 5) Common errors include configuration syntax errors and permission issues, and debugging skills include using nginx-t command and stub_status module. 6) Performance optimization suggestions include adjusting worker parameters, using gzip compression and

Nginx Troubleshooting: Diagnosing and Resolving Common ErrorsNginx Troubleshooting: Diagnosing and Resolving Common ErrorsMay 05, 2025 am 12:09 AM

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.

Deploying Applications with NGINX Unit: A GuideDeploying Applications with NGINX Unit: A GuideMay 04, 2025 am 12:03 AM

NGINXUnitischosenfordeployingapplicationsduetoitsflexibility,easeofuse,andabilitytohandledynamicapplications.1)ItsupportsmultipleprogramminglanguageslikePython,PHP,Node.js,andJava.2)Itallowsdynamicreconfigurationwithoutdowntime.3)ItusesJSONforconfigu

NGINX and Web Hosting: Serving Files and Managing TrafficNGINX and Web Hosting: Serving Files and Managing TrafficMay 03, 2025 am 12:14 AM

NGINX can be used to serve files and manage traffic. 1) Configure NGINX service static files: define the listening port and file directory. 2) Implement load balancing and traffic management: Use upstream module and cache policies to optimize performance.

NGINX vs. Apache: Comparing Web Server TechnologiesNGINX vs. Apache: Comparing Web Server TechnologiesMay 02, 2025 am 12:08 AM

NGINX is suitable for handling high concurrency and static content, while Apache is suitable for dynamic content and complex URL rewrites. 1.NGINX adopts an event-driven model, suitable for high concurrency. 2. Apache uses process or thread model, which is suitable for dynamic content. 3. NGINX configuration is simple, Apache configuration is complex but more flexible.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools