Nginx: Custom Error 403 Page Not Working with IP Deny Configuration

If you are using the deny directive in your Nginx configuration to block access to certain IP addresses or ranges, you may find that your custom error page for HTTP 403 Forbidden errors is not being displayed for denied requests. This is because when a request is denied by the deny directive, Nginx returns a 403 response directly, without going through the standard request processing pipeline that would trigger the custom error page.

To display a custom error page for denied requests, you can use the error_page directive in combination with a named location. Here is an example configuration:

http {
server {
listen 80;
server_name example.com;

# Custom error page for 403 Forbidden
error_page 403 /403.html;
location = /403.html {
root /var/www/html;
internal;
}

# Deny requests from specific IP addresses
location / {
deny 10.0.0.1;
deny 10.0.0.2;
# ... other deny rules ...
try_files $uri $uri/ /index.html;
}
}
}

In this example, the error_page directive specifies a named location for the custom error page, which is located at /var/www/html/403.html. The location block for the named location uses the root directive to specify the directory where the error page is located, and the internal directive to ensure that the named location is not accessible directly from the web. This means that the only way to access the error page is through the error_page directive.

The location / block contains the deny directives to block requests from specific IP addresses, and the try_files directive to serve the main content of the website. When a request is denied by one of the deny rules, Nginx will return a 403 response, which will trigger the error_page directive to display the custom error page.

With this configuration, requests from the denied IP addresses will be blocked and a custom error page will be displayed for 403 Forbidden errors.

Leave a Comment