When a user encounters a page not found (404 error) on a website, it’s crucial to provide a user-friendly and informative experience. Allows you to customize the 404 error page to match the look and feel of your site. In this guide, we’ll walk through the steps to configure Nginx for a custom 404 error page.
Step 1: Create the Custom 404 Page
Before configuring Nginx, create a custom HTML file for the 404 error page. For example, you can name it 404.html
and design it to suit your website’s design and branding.
sudo nano /usr/share/nginx/html/404.html
Add your HTML content and save the file.
Step 2: Configure Nginx
Now, let’s configure Nginx to use the custom 404 page. Open the Nginx configuration file in a text editor. The main configuration file is often located at /etc/nginx/nginx.conf
or /etc/nginx/sites-available/default
.
sudo nano /etc/nginx/nginx.conf
Alternatively, if you have a site-specific configuration, edit that file.
sudo nano /etc/nginx/sites-available/yoursite.com
Step 3: Add Error Page Directive
Locate the server
block in the configuration file. Add or modify the error_page
directive to specify the custom 404 page.
server {
# other server configurations
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
internal;
}
# other server configurations
}
This configuration tells Nginx to serve the custom 404 page when a 404 error occurs. The location
block ensures that only internal requests can access the 404 page.
Step 4: Test and Reload Nginx
After saving the changes, test the configuration to ensure there are no syntax errors.
sudo nginx -t
If the test is successful, reload Nginx to apply the changes.
sudo systemctl reload nginx
Congratulations! You have successfully configured Nginx to use a custom 404 error page. This small adjustment can significantly enhance the user experience by providing a more personalized and branded error page when visitors encounter broken links or unavailable content on your website.