How to create custom error pages for specific HTTP error codes in Nginx?

To create custom error pages for specific HTTP error codes in Nginx, you can use the error_page directive in your configuration file. Here's how you can do it:

  1. Open your Nginx configuration file. This is typically located at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf.

  2. Locate the http block in the configuration file. If it doesn't exist, create one.

  3. Within the http block, add the error_page directive to specify the custom error page for a specific HTTP error code. The syntax is as follows:

error_page <error_code> <custom_page>;

Replace <error_code> with the HTTP error code you want to handle, and <custom_page> with the path to your custom error page.

For example, to create a custom error page for the 404 Not Found error, you can add the following line:

error_page 404 /path/to/custom404.html;
  1. Optionally, you can also create a default custom error page for all other HTTP error codes that are not explicitly defined. To do this, add the following line:
error_page 500 /path/to/default_error.html;

Replace /path/to/default_error.html with the path to your default error page.

  1. Save the configuration file.

  2. Test the configuration to check for syntax errors:

sudo nginx -t

If there are no errors, proceed to the next step. Otherwise, fix the errors and test again.

  1. Restart or reload Nginx for the changes to take effect:
sudo service nginx restart

That's it! Now, when a client encounters the specified HTTP error code, Nginx will serve the corresponding custom error page you have defined. Make sure to provide the correct paths to your custom error pages.