matth3o matth3o - 9 months ago 114
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;

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

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 !


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.


In the 404.html

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

In nginx config

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

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">