如何在 Nginx 中故意造成 400 Bad Request?

How to intentionally cause a 400 Bad Request in Nginx?

我把我的 一分为二。

我的 REST API 的一位使用者说,有时我 return 发出 400 错误请求 - 客户端发送的请求在语法上不正确。错误。

我的应用程序 (Python/Flask) 日志似乎没有捕捉到这一点,我的 webserver/Nginx 日志也没有。

我更改了默认的 400 和 404 错误消息 HTML,方法是在配置中添加以下行(并在正确的目录中添加相应的 HTML 页面):

    error_page  404              /404.html;
    location = /404.html {
        root   html;
    }
    error_page  400              /400.html;
    location = /400.html {
        root   html;
    }

此错误消息明确指出 "Nginx",因此我知道 Nginx 正在提供 400 而不是我的 python/flask 应用程序(其 400 已更改为明确状态 "Flask")。

有没有一种方法可以让 Nginx return 出现 400 错误,可能是通过 python、CURL 或 Postman?比如我也改了404错误页面,可以通过调用无效的URL.

故意让Nginxreturn对应错误HTML

Nginx 将 return 状态代码 400 如果它收到一个 header 字段大于配置的 large_client_header_buffers

A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

来源:http://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers

所以你只需要创建一个 header 大于 8k 的 curl 请求。这是一个使用 python 位生成 header 变量传递给 curl 的示例:

(nginx)macbook:nginx joeyoung$ myheader=$(python -c "print 'A'*9000")
(nginx)macbook:nginx joeyoung$ curl -vvv --header "X-MyHeader: $myheader" http://my.example.website.com

结果:

...
> 
< HTTP/1.1 400 Bad Request
< Server: nginx/1.4.7
< Date: Wed, 02 Sep 2015 22:37:29 GMT
< Content-Type: text/html
< Content-Length: 248
< Connection: close

在 NGINX 的配置中创建一个位置到 return 400 错误:

location /error { 
    return 400;
}

Presto.