82

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?

Blieque
  • 670
  • 7
  • 28
shanqn
  • 1,155
  • 2
  • 9
  • 14

3 Answers3

128
location /test/ {
  return 404;
}
Vicheanak
  • 6,444
  • 17
  • 64
  • 98
  • 4
    [`return` is part of the `HttpRewriteModule`](http://wiki.nginx.org/HttpRewriteModule#return). It makes its parent location always return the given status, which is exactly what the requestor wants. – Sam Hanes Jun 15 '12 at 01:46
  • 1
    If you only want it to match the exact route then you can use `location = /test/ { ... }` – David A Jan 06 '19 at 22:00
42

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

Grant McLean
  • 6,898
  • 1
  • 21
  • 37
Chuan Ma
  • 9,754
  • 2
  • 45
  • 37
10
location ^~ /test/ {
    internal;
}
Jim
  • 72,985
  • 14
  • 101
  • 108
  • 13
    [`internal` (from the `HttpCore` module)](http://wiki.nginx.org/HttpCoreModule#internal) marks the location as internal to the server. It will return 404 for external requests but can still be the target of internal redirects, rewrites, error pages, etc. – Sam Hanes Jun 15 '12 at 01:48