'nginx: load 404 page if location is not matched with given url

in nginx.conf I have used this

try_files $uri $uri/ /index.php;

so that when user type any url the index.php will load.

but now I have some list of url. like [blog, contact, faq]

so when user hit anything out of that url. for example, /test I want to display the 404 page.

how can I achieve that?

here is the location block

location / {
             auth_basic "Restricted Content";
             auth_basic_user_file /etc/nginx/.htpasswd;
             try_files $uri $uri/ /index.php;

         }


Solution 1:[1]

If it's a long list, use a map, but if its a short list, add extra location rules:

location = /test { return 404; }

If you want these rules to be subject to your auth_basic, either nest them within the location / block, or if possible, move the auth_basic statements into the outer block.

Solution 2:[2]

Use the map block, e.g.:

map $uri $correct_route {
    /blog    1;
    /contact 1;
    /faq     1;
    # default value will be an empty string
}
server {
    ...
    auth_basic "Restricted Content";
    auth_basic_user_file /etc/nginx/.htpasswd;
    location / {
        try_files $uri $uri/ @check_route;
    }
    location @check_route {
        if ($correct_route) { rewrite ^ /index.php last; }
        return 404;
    }
    ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Richard Smith
Solution 2 Ivan Shatsky