从413更改nginx响应代码

时间:2017-09-11 17:38:54

标签: nginx httpresponse

有没有办法改变nginx发送的响应代码?当服务器收到超过配置中定义的client_max_body_size的文件时,我可以让它返回403代码而不是413代码吗?

1 个答案:

答案 0 :(得分:2)

以下对我来说很好

events {
    worker_connections  1024;
}
http {
server {
   listen 80;

    location @change_upload_error {
       return 403 "File uploaded too large";
    }

    location /post {
       client_max_body_size 10K;
       error_page 413 = @change_upload_error;
       echo "you reached here";
    }
}

}

发布50KB文件的结果

$ curl -vX POST -F file=@test.txt vm/post
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 192.168.33.100...
* TCP_NODELAY set
* Connected to vm (192.168.33.100) port 80 (#0)
> POST /post HTTP/1.1
> Host: vm
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Length: 51337
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------67df5f3ef06561a5
>
< HTTP/1.1 403 Forbidden
< Server: openresty/1.11.2.2
< Date: Mon, 11 Sep 2017 17:58:55 GMT
< Content-Type: text/plain
< Content-Length: 23
< Connection: close
<
* Closing connection 0
File uploaded too large%

和nginx日志

web_1       | 2017/09/11 17:58:55 [error] 5#5: *1 client intended to send too large body: 51337 bytes, client: 192.168.33.1, server: , request: "POST /post HTTP/1.1", host: "vm"
web_1       | 192.168.33.1 - - [11/Sep/2017:17:58:55 +0000] "POST /post HTTP/1.1" 403 23 "-" "curl/7.54.0"