Nginx | Create custom 404 page not found error page
Written by Guillermo Garron
Date: 2010-12-06 10:50:30 00:00
Introduction
I'm working with Nginx since more than a year ago, it is an extremely fast web server, specially to work in front of Apache serving static content.
Well, if you need to customize your 404 (file not found) error page in Nginx, you are in the right place.
First what is a 404 error, from Wikipedia:
The 404 or Not Found error message is a HTTP standard response code indicating that the client was able to communicate with the server, but the server could not find what was requested. 404 errors should not be confused with "server not found" or similar errors, in which a connection to the destination server could not be made at all. A 404 error indicates that the requested resource may be available again in the future
Creating your own 404 error page
In the event some of your users get a 404 (page not found) error, it is better if you provide him with a good page, so he can stay at your site.
Some simple example can be this one:
<html>
<Title>Page Not Found</title>
<h2>Page Not Found</h2>
<p>We're very sorry to inform you that the page you are looking for could not be found, please accept our apologies, and follow one of the following options</p>
<ol>
<li>Contact the <a href="mailto:webmaster@site.com">webmaster</a> and send him the link of the page you were trying to reach, and the page where it is published</li>
<li>Go to our <a href="http://www.site.com">Homepage</a>, and use our search box, to find what you were looking for.</li>
</ol>
</html>
Configure Nginx to use your custom page
Now to make Nginx use your custom page instead of the default one, edit the file nginx.conf which could be at /etc/nginx/
Inside the server section, add:
error_page 404 /404.html;
It is a good idea, to block the access to that page, unless there is an error, so add this below the above line:
location /404.html {
internal;
}
So the complete and simple conf file may look like this:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
server {
listen 80;
server_name localhost;
location / {
root /srv/http/nginx;
index index.html index.htm;
}
error_page 404 /404.html;
location /404.html {
internal;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}