Home > Blockchain >  How to Use a Single Custom Error Page for all 404 Requests
How to Use a Single Custom Error Page for all 404 Requests

Time:12-28

I have created a custom 404 page for resources that dont exist.

It works with all endpoints except the ones which have /api/v1/, where I get the default NGINX 404 page.

I have domain.name.conf file in /etc/nginx/conf.d/:

server {
    listen 80;
    listen [::]:80;
    server_name domain.name www.domain.name;

    root /var/www/domain.name/public_html;
    error_page 404 /not_found.html;

    location /api/v1/ {
        proxy_pass http://localhost:8080/;
        limit_except GET HEAD { deny all; }
    }

    location / {
        index index.html;
        try_files $uri $uri/ =404;
    }

    location = /not_found.html {
        internal;
    }
}

On adding the $try_files directive inside /api/v1/, "Hello, World!" from the backend REST API is not displayed at /api/v1/hello, even though its a valid endpoint. Instead I get the custom 404 error page:

server {
    listen 80;
    listen [::]:80;
    server_name domain.name www.domain.name;

    root /var/www/domain.name/public_html;
    error_page 404 /not_found.html;

    location /api/v1/ {
        proxy_pass http://localhost:8080/;
        try_files $uri =404;
        limit_except GET HEAD { deny all; }
    }

    location / {
        index index.html;
        try_files $uri $uri/ =404;
    }

    location = /not_found.html {
        internal;
    }
}

How can I use a single custom error page for all non existing resources ?

CodePudding user response:

Thanks to Richard Smith's comment, the conf file look like:

server {
    listen 80;
    listen [::]:80;
    server_name domain.name www.domain.name;

    root /var/www/domain.name/public_html;
    error_page 404 /not_found.html;

    proxy_intercept_errors on;

    location /api/v1/ {
        proxy_pass http://localhost:8080/;
        limit_except GET HEAD { deny all; }
    }

    location / {
        index index.html;
        try_files $uri $uri/ =404;
    }

    location = /not_found.html {
        internal;
    }
}
  • Related