How to globally add exception handler configuration to server block under /etc/nginx/sites-available?

27 Views Asked by At

I want to apply a solution for 403 forbidden default error. I have 100s of sites under /etc/nginx/sites-available. I created a 403.html file (/usr/share/nginx/html) and added the following code in the */etc/nginx/snippets/custom_exception.conf *

    error_page 403 /403.html;

    location = /403.html {
       root /usr/share/nginx/html;
    }

I tested this code for one site by adding the following line

include /etc/nginx/snippets/custom_exception.conf;

It's working fine. The code should be in the server block of every file. Issue is I am not convinced to make this change for each and every file in the production server.

I have tried couple of ways in the nginx.conf file as follows, yet not working

http {
...
 
 include /etc/nginx/snippets/custom_exception.conf;
 include /etc/nginx/conf.d/*.conf;
 include /etc/nginx/sites-enabled/*;

}
http {
...
 server {
    include /etc/nginx/snippets/custom_exception.conf;
 }

  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;

}
1

There are 1 best solutions below

0
Richard Smith On

The error_page directive can be placed in http context.

Unfortunately, the location directive (or the include file that contains it) must be copied into every relevant server block.

At least, if you edit every server block to add an include statement - you will only ever need to do it the one time.


Alternatively, if this works for you and your clients, you put the 403.html page into a separate domain and specify the full URL in the error_page statement. This removes the requirement to edit every server block.

For example:

error_page 403      http://example.com/forbidden.html;