Configuring nginx to return a 404 when a URL matches a pattern

NginxWebserver

Nginx Problem Overview


I want nginx to return a 404 code when it receives a request which matches a pattern, e.g., /test/*. How can I configure nginx to do that?

Nginx Solutions


Solution 1 - Nginx

location /test/ {
  return 404;
}

Solution 2 - Nginx

Need to add "^~" to give this match a higher priority than regex location blocks.

location ^~ /test/ {
  return 404;
}

Otherwise you will be in some tricky situation. For example, if you have another location block such as

location ~ \.php$ {
  ...
}

and someone sends a request to http://your_domain.com/test/bad.php, that regex location block will be picked by nginx to serve the request. Obviously it's not what you want. So be sure to put "^~" in that location block!

Reference: https://nginx.org/en/docs/http/ngx_http_core_module.html#location

Solution 3 - Nginx

location ^~ /test/ {
    internal;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshanqnView Question on Stackoverflow
Solution 1 - NginxVicheanakView Answer on Stackoverflow
Solution 2 - NginxChuan MaView Answer on Stackoverflow
Solution 3 - NginxJimView Answer on Stackoverflow