Creating a fallback error page for nginx when root directory does not exist
- by Ruirize
I have set up an any-domain config on my nginx server - to reduce the amount of work needed when I open a new site/domain. This config allows me to simply create a folder in /usr/share/nginx/sites/ with the name of the domain/subdomain and then it just works.™
server {
# Catch all domains starting with only "www." and boot them to non "www." domain.
listen 80;
server_name ~^www\.(.*)$;
return 301 $scheme://$1$request_uri;
}
server {
# Catch all domains that do not start with "www."
listen 80;
server_name ~^(?!www\.).+;
client_max_body_size 20M;
# Send all requests to the appropriate host
root /usr/share/nginx/sites/$host;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ =404;
}
recursive_error_pages on;
error_page 400 /errorpages/error.php?e=400&u=$uri&h=$host&s=$scheme;
error_page 401 /errorpages/error.php?e=401&u=$uri&h=$host&s=$scheme;
error_page 403 /errorpages/error.php?e=403&u=$uri&h=$host&s=$scheme;
error_page 404 /errorpages/error.php?e=404&u=$uri&h=$host&s=$scheme;
error_page 418 /errorpages/error.php?e=418&u=$uri&h=$host&s=$scheme;
error_page 500 /errorpages/error.php?e=500&u=$uri&h=$host&s=$scheme;
error_page 501 /errorpages/error.php?e=501&u=$uri&h=$host&s=$scheme;
error_page 503 /errorpages/error.php?e=503&u=$uri&h=$host&s=$scheme;
error_page 504 /errorpages/error.php?e=504&u=$uri&h=$host&s=$scheme;
location ~ \.(php|html) {
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_intercept_errors on;
}
}
However there is one issue that I'd like to resolve, and that is when a domain that doesn't have a folder in the sites directory, nginx throws an internal 500 error page because it cannot redirect to /errorpages/error.php as it doesn't exist.
How can I create a fallback error page that will catch these failed requests?