Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGINX custom 404 page without redirect

Tags:

nginx

By default, when NGINX returns a 404 it renders some default HTML. For example, something like:

<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.10.0 (Ubuntu)</center>
</body>
</html>

I'd like to customize this HTML but leave the URL unchanged. I've tried setting the error page for 404s:

error_page 404 /404.html

But this first redirects the browser to /404.html.

Is there a way to customize the 404 HTML without redirecting?

like image 763
scttnlsn Avatar asked Oct 06 '16 00:10

scttnlsn


People also ask

How do I create a 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.

How to add custom error Pages in nginx?

Creating Your Custom Error PagesPut 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 .

What is 404 not found nginx?

Essentially, the “404 error” indicates that your or your visitor's web browser was connected successfully to the website server or the host. However, it was unable to locate the requested resource, such as filename or any specific URL.


2 Answers

may be you can do it as follow by using the error_page and proxy_intercept_errors directive of nginx

detail config

server {
    ## other config
    ## here the proxy_intercept_errors directive is the key
    proxy_intercept_errors on;
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        ## your 50x.html file parent directory
        root   /var/www; 
    }
    error_page   404  /404.html;
    location = /404.html {
        ## your 404.html file parent directory
        root   /var/www; 
    }
}

document on nginx official site:

proxy_intercept_errors and error_page

like image 143
rhtsjz Avatar answered Oct 17 '22 21:10

rhtsjz


This configuration worked for me

error_page 404 /404.html;
location = /404.html {
    internal;
}

http://nginx.org/en/docs/http/ngx_http_core_module.html#internal

like image 28
adam187 Avatar answered Oct 17 '22 21:10

adam187