A Virtual Home - nginxhttps://blog.avirtualhome.com/2018-03-23T08:03:00-04:00Create a custom 410 error page in NGINX2018-03-23T08:03:00-04:002018-03-23T08:03:00-04:00Peter van der Doestag:blog.avirtualhome.com,2018-03-23:/create-custom-410-error-page-nginx/<p>I had a need to create a 410 page for a whole bunch pages. As it turns out it was not as easy as it sounds</p><p>When converting this blog from WordPress to Pelican I decided I just ditch a whole bunch of articles I had written in WordPress. According to several articles on the net it is best practice to have pages you delete return a 410 page. For a better user experience I wanted used to land on a page that looks like part of the blog.</p>
<p>As I’m using <span class="caps">NGINX</span> you can utilize the map function to create a new variable whose value depends on values of one or more of the source variables specified in the first parameter. I created a file called <code>old_request.nginx</code> in the directory <code>/etc/nginx/snippets/</code></p>
<div class="highlight"><pre><span></span>map $request_uri $gone_var {
/the-avh-amazon-plugin-has-reached-its-end-of-life/ 1;
/wordpress-plugin-update-avh-first-defense-against-spam-v3-0/ 1;
/end-of-the-avh-amazon-plugin/ 1;
/wordpress-plugin-update-avh-extended-categories/ 1;
}
</pre></div>
<p>This file just needs to be included in your configuration file, and if you want to have a custom 410 error page you just have to tell <span class="caps">NGINX</span> which file to use when it encounters a 410 error.</p>
<div class="highlight"><pre><span></span>include snippets/old_request.nginx;
server {
....
error_page 404 /404.html;
error_page 410 /410.html;
if ($gone_var) {
return 410;
}
location / {
....
}
}
</pre></div>
<p>Easy enough, <strong><span class="caps">NOT</span></strong>. The above configuration does not work. If you try to browse one of the URLs mentioned in the the <code>old_request.nginx</code> file you get the default <span class="caps">NGINX</span> 410 error page and not the file you said it should show.</p>
<p>To fix this we have to use a named location. A named location has the <code>@</code> prefix. Such a location is not used for a regular request processing, but instead used for request redirection.</p>
<div class="highlight"><pre><span></span>include snippets/old_request.nginx;
server {
....
error_page 404 /404.html;
error_page 410 @gone;
if ($gone_var) {
return 410;
}
location @gone {
rewrite ^(.*)$ /410.html break;
}
location / {
....
}
}
</pre></div>
<p>And now your custom 410 error page works.</p>