Vapor + Nginx 解除请求大小限制
in 技术 with 0 comment

Vapor + Nginx 解除请求大小限制

in 技术 with 0 comment

问题

Vapor 默认大小是 1 * 1000 * 1000(单位 Byte),换算出来 < 1 MB。如果 HTTP Body 超过该大小则报错:

[ERROR] [HTTP] [HTTP] Request size exceeded maximum, connection closed. [HTTPServer.swift:170]
[ ERROR ] stream ended at an unexpected time (/Users/liu/Documents/workspace/UserServer/.build/checkouts/vapor.git-5492988889259800272/Sources/Vapor/Logging/Logger+LogError.swift:32)

思路

[HTTPServer.swift:170]

根据上面的错误提示,找到下面的相关代码行。得到关键字 self.maxBodySize

if existing.readableBytes + chunk.readableBytes > self.maxBodySize {
     ERROR("[HTTP] Request size exceeded maximum, connection closed.")
     ctx.close(promise: nil)
}

然后顺藤摸瓜 HTTPServerHandler -> HTTPServer -> NIOServer -> NIOServerConfig,终于找到原点了。NIOServerConfig 已经被注入到 Services

//app.swift line 13
var services = Services.default()

//Services+Default.swift line 11
services.register(NIOServerConfig.self)

解决办法

已经注入的 Service 是无法修改的,但是可以重新注入覆盖(会在后续的 Vapor 源码解读中解释):

//configure.swift  func configure
var nioServerConfig = NIOServerConfig.default()
//修改为 4MB
nioServerConfig.maxBodySize = 4 * 1024 * 1024
services.register(nioServerConfig)

Nginx

问题

Nginx 默认 body size 为 1MB,如果超过则会返回如下页面:

<html>
    <head>
        <title>413 Request Entity Too Large</title>
    </head>
    <body bgcolor="white">
        <center>
            <h1>413 Request Entity Too Large</h1>
        </center>
        <hr>
        <center>nginx/1.10.3 (Ubuntu)</center>
    </body>
</html>

解决办法

编辑 /etc/nginx/nginx.conf,在 http{} 块里面加入如下行:

client_max_body_size 4m;

最后重启即可:

sudo /etc/init.d/nginx reload
Responses