Search code examples
nginxreturnhttp-status-code-404

returning 404 in nginx location block


server{

    include /etc/nginx/mime.types;
    listen 18081;
    root /home/maxou;
    error_page 404 /webserv/error/404.html;

    location \.css
    {
        root /home/maxou/webserv/error;
    }

    location ~ /images {
    return 404;
}

When I try to access a uri starting with images/ I get my custom 404.html error page but without the css. The GET uri for my css is /images/somefile.css and of course dont find it because it is located in /webserv/error. I dont understand why the css extension block doesnt have the priority on the /images block since I have no optional modifier. What am I doing wrong ? How to return a 404 code with my custom html and css with the routes /images ?


Solution

  • Your location is wrong

    location \.css
    

    For regexp location, you must use ~ or ~* modifier, like:

    location ~* \.css
    

    nginx location Regular expressions are specified with the preceding “~*” modifier (for case-insensitive matching), or the “~” modifier (for case-sensitive >matching).

    suppose 404.html and style.css locate in /var/www/html/custom_errors,
    link tag in 404.html:
    <link rel="stylesheet" href="custom_errors/style.css">
    then config will be something like:

    error_page 404 /404.html;
    location = /404.html{
      root /var/www/html/custom_errors;
      internal;
    }
    location ~ /images {
      return 404;
    }
    

    Now if request http://hostname.tld/images, you'll get custom 404 error page with your css style.