Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx: how to always return a custom 404 page for the default host

Tags:

nginx

I have nginx 0.8.53 configured with some virtual hosts which work as desired. However, due to nginx's "best match" on virtual hosts, I need to add a default host to catch all requests that aren't for a specific virtual host. I would like the default host to return a custom 404 page that I created instead of the default nginx 404 page.

I assumed I needed something like:

# The default server: server {     listen       80 default_server;     server_name  everythingelse;      # Everything is a 404     location / {         return 404;     }     error_page 404 /opt/local/html/404.html; } 

But this still returns the default nginx 404 page. It seems the return 404 ignores the error_page config.

like image 235
Tim P Avatar asked Sep 23 '11 09:09

Tim P


People also ask

How do I change the default 404 page in nginx?

Create a configuration file called custom-error-page. conf under /etc/nginx/snippets/ as shown. This configuration causes an internal redirect to the URI/error-page. html every time NGINX encounters any of the specified HTTP errors 404, 403, 500, and 503.

Where are nginx default error pages?

Creating Your Custom Error Pages Put your custom error pages in the /usr/share/nginx/html directory where Nginx sets its default document root. You'll make a page for 404 errors called custom_404. html and one for general 500-level errors called custom_50x. html .


2 Answers

Here what I have in my conf to make it work:

# The default server. server {   listen       80 default_server;   server_name  everythingelse;    error_page 404 /404.html;    # Everything is a 404   location / {     return 404; #return the code 404   }    # link the code to the file   location = /404.html {     #EDIT this line to make it match the folder where there is your errors page     #Dont forget to create 404.html in this folder     root  /var/www/nginx/errors/;   } } 
like image 96
0x1gene Avatar answered Oct 08 '22 07:10

0x1gene


Very few directives in nginx take a filesystem path. You want something like:

# The default server. server {   listen       80 default_server;   server_name  everythingelse;    root /opt/local/html;    error_page 404 /404.html;    # Everything is a 404   location / {     return 404;   }    # EDIT: You may need this to prevent return 404; recursion   location = /404.html {     internal;   } } 
like image 39
kolbyjack Avatar answered Oct 08 '22 08:10

kolbyjack