matth3o matth3o - 5 months ago 86
CSS Question

nginx - custom 404 - css / js not found

I have an nginx server running with

error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
internal;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
internal;
}


The error pages are well displayed as long as the url is "http://domain/not_existing_page.html".
However if it is like "http://domain/subpath/not_existing_page.html", my CSS and JS are not retrieved.

Indeed, in my 404.html the link

<link href="css/custom.css" rel="stylesheet">


doesn't work as the browser looks for "http://domain/subpath/css/custom.css".

Is there a way to configure nginx so that my 404.html always gets my css and js from / ?

Thanks for your help !

Answer

You need to design your error pages with absolute paths to the resources, and optionally prefix it with something unique so you can set the correct root path for them, too.

Example:

In the 404.html

<link href="/error-pages/css/custom.css" rel="stylesheet">

In nginx config

location ~ "^/error-pages" {
        root   /usr/share/nginx/html;
        internal;
}

If your css/js resources for the error pages are placed in the global document root, then it's enough to use an absolute path like

<link href="/css/custom.css" rel="stylesheet">