http
{
include mime.types;
default_type application/octet-stream;
source_charset GB2312;
server_names_hash_bucket_size 256;
client_header_buffer_size 8k;#默认是4k
large_client_header_buffers 4 8k;
......
}
看到huoding.com上有比较好的帖子,于是理解并用自己的话来描述啦
加大client_header_buffer_size和large_client_header_buffers可以解决问题,但是为毛要两个参数来控制呢?一个不久可以满足要求了么?
client_header_buffer_size用来缓存请求头,如果超过的话就会返回400错误了。但是如果绝大多数请求不会超过这个值的话,那么更大的请求头可以受large_client_headers_buffers的影响。
还是贴nginx的原话吧
- client_header_buffer_size: Sets buffer size for reading client request header. For most requests, a buffer of 1K bytes is enough. However, if a request includes long cookies, or comes from a WAP client, it may not fit into 1K. If a request line or a request header field does not fit into this buffer then larger buffers, configured by the large_client_header_buffers directive, are allocated.
- large_client_header_buffers: Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. 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.
用两个参数来控制缓存大小的原因是为了平衡内存资源和处理速度的矛盾。
查找原因后得知是nginx在转发请求时会默认忽略带有"_"下划线的头信息
解决nginx转发websocket报400错误
说明
由于个人服务器上面有多个项目,配置了二级域名,需要对二级域名进行转发,在转发工作这快采取了大名鼎鼎的nginx
。在这之前所有的项目运行转发都没问题,然而今天在部署一个具有websocket
通信的项目时,却意外的报错了,错误消息如下:
1failed: Error during WebSocket handshake: Unexpected response code: 400
。这个错误在本地测试环境以及访问非nginx
转发都没有问题,由此推断出问题应该出现在nginx
转发这个环节。
于是,在google
的帮助下,看到了socket.io
官方issues
有关于这个问题的讨论,链接:https://github.com/socketio/socket.io/issues/1942
解决方案
看了下讨论区说的方案,问题出现在nginx
的配置文件,需要修改nginx.conf
文件。在linux
终端中敲入vim /etc/nginx/nginx.conf
,找到location
这个位置,配置文件如下所示:
1server {
2 listen 80;
3 server_name school.godotdotdot.com;
4 charset utf-8;
5
6 location / {
7 proxy_pass http://127.0.0.1:3000;
8 proxy_set_header Host $host;
9 proxy_http_version 1.1;
10 proxy_set_header Upgrade $http_upgrade;
11 proxy_set_header Connection "upgrade";
12 proxy_set_header X-Real-IP $remote_addr;
13 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
14 proxy_connect_timeout 60;
15 proxy_read_timeout 600;
16 proxy_send_timeout 600;
17 }
18
19 error_page 500 502 503 504 /50x.html;
20 location = /50x.html {
21 root html;
22 }
23
24 }
其中最重要的是下面这三行
1proxy_http_version 1.1;
2proxy_set_header Upgrade $http_upgrade;
3proxy_set_header Connection "upgrade";
其中第一行是告诉nginx
使用HTTP/1.1
通信协议,这是websoket
必须要使用的协议。
第二行和第三行告诉nginx
,当它想要使用WebSocket时,响应http
升级请求。
nginx反向代理Authorization请求头问题解决
在前后端分离的开发中使用nginx做反向代理去请求服务器地址时,发现自定义的header请求头Authorization信息丢失了,在网上找了很多资料都不是我所需要的,现解决后记录如下:
修改nginx的nginx.conf配置文件,添加如下红框所示内容。