Home > Net >  nginx: load 404 page if location is not matched with given url
nginx: load 404 page if location is not matched with given url

Time:02-08

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;

         }

CodePudding user response:

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.

CodePudding user response:

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;
    }
    ...
}
  •  Tags:  
  • Related