nginx如何把日志推送到远程服务器与其如何配置websocket
log_format common "$remote_addr,$http_ip,$http_mac,$time_local,$status,$request_length,$bytes_sent,$body_bytes_sent,$http_user_agent,$http_referer,$request_method,$request_time,$request_uri,$server_protocol,$request_body,$http_token";
log_format main "$remote_addr,$http_ip,$http_mac,$time_local,$status,$request_length,$bytes_sent,$body_bytes_sent,$http_user_agent,$http_referer,$request_method,$request_time,$request_uri,$server_protocol,$request_body,$http_token";
access_log logs/access.log common;
access_log syslog:server=192.168.1.10:9999,facility=local7,tag=nginx,severity=info main;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
配置解析:将nginx的日志各项参数以逗号分割形式输出,同时nginx将nginx日志实时推送到192.168.1.10:9999上,这时候我们可以在192.168.1.10服务器上部署一个tcp/udp服务,监听端口9999,并在防火墙开放9999端口,我们编写的tcp/udp就能实时接收到nginx推送过来的日志,然后将nginx日志实时收集到某个存储集群中,就可以对nginx日志进行统一存储、维护和分析。
map $http_upgrade $connection_upgrade {
default upgrade;
close;
upstream wsbackend{
server ip1:port1;
server ip2:port2;
keepalive 1000;
}
server {
listen 20038;
location /{
proxy_http_version 1.1;
proxy_pass http://wsbackend;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_read_timeout 3600s;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
该配置表达的是如果$http_upgrade不为空,则$connection_upgrade为upgrade,如果$http_upgrade为空,则$connection_upgrade为close。
upstream wsbackend{
server ip1:port1;
server ip2:port2;
keepalive 1000;
}
server {
listen 20038;
location /{
proxy_http_version 1.1;
proxy_pass http://wsbackend;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_read_timeout 3600s;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
listen 20038:表示nginx监听的端口
locations / :表示监听的路径(/表示所有路径,通用匹配,相当于default)
proxt_http_version 1.1L表示反向代理发送的HTTP协议的版本是1.1,HTTP1.1支持长连接
proxy_pass http://wsbackend;:表示反向代理的uri,可以使用负载均衡变量
proxy_redirect off; 表示不要替换路径,如果是/,这个有没有都没关系,因为default也是将路径替换到proxy_pass的后边
proxy_set_header Host $host; 表示传递时请求头不变, $host是nginx内置变量,表示的是当前的请求头,proxy_set_header表示设置请求头
proxy_set_header X-Real-IP $remote_addr; 表示传递时来源的ip还是现在的客户端的ip
proxy_read_timeout 3600s;表的两次请求之间的间隔超过 3600s 后才关闭这个连接,默认的60s,自动关闭的元凶
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 表示X-Forwarded-For头不发生改变
proxy_set_header Upgrade $http_upgrade; 表示设置Upgrade不变
proxy_set_header Connection $connection_upgrade; 表示如果 $http_upgrade为upgrade,则请求为upgrade(websocket),如果不是,就关闭连接