nginx 负载均衡和反向代理的基本配置

2016-08-12  本文已影响0人  wmtcore

负载均衡

upstream

    upstream backend {
        server 127.0.0.1:5566 weight=1 max_fails=2 fail_timeout=30s;
    }

    server {
        location / {
            proxy_pass http://backend; #backend指上游服务器
        }
    }

server
parameters 定义
weight=number 上游服务器转发的权重 默认1
max_fails=number 在fail_timeout时间内,如果向上游服务器转发失败次数超过number,就认为该服务器在此时间段里不可用,默认1 设为0就不检查失败次数
fail_timeout=time 用于优化反向代理功能,与连接、读取、响应超时无关,默认10秒
down 永久下线服务器,只在使用ip_hash有效
backup 在使用ip_hash时无效 表示上游服务器只是备份服务器,只有在所有非备份上游服务器失效后,才会指向备份
ip_hash

先根据客户端的ip地址计算一个key,将可以按照upstream集群的上游服务器数量进行取模,再根据取模的结果把请求地址转发到相应的上游服务器,不能与weight同时使用,在标识上游服务器不可用时,要用down不能直接删除,确保转发策略一贯性

    upstream backend {
        ip_hash;
        server 127.0.0.1:5566 weight=1 max_fails=2 fail_timeout=30s;
        server backend down;
    }

记录日志时支持的变量

变量名 定义
$upstream_addr 处理请求的上游服务器地址
$upstream_cache_status 表示是否命中缓存,取值范围:MISS、EXPIRED、UPDATING、SATLE、HIT
$upstream_status 上游服务器返回的响应中HTTP响应码
$upstream_response_time 上游服务器响应时间,精度毫秒
$upstream_http_$HEADER http头部,如upstream_http_host
log_format timing '$remote_addr - $remote_user [$time_local] $request '
    'upstream_response_time $upstream_response_time '
    'msec $msec request_time $request_time';

log_format up_head '$remote_addr - $remote_user [$time_local] $request '
    'upstream_http_content_type $upstream_http_content_type'

反向代理配置

proxy_pass

将当前请求反向代理到URL参数指定的服务器上,URL可以是主机名或ip地址

proxy_pass http://localhost:3000/uri/;

可以加上负载均衡 使用upstream
upstream backend {...}
server {location / {
            proxy_pass http://backend; #backend指上游服务器
        }}

可以把httpz转换成https
proxy_pass https://192.168.0.1/;

若需要转发host头部
proxy_set_header Host $host;

proxy_method

转发时的协议方法名
proxy_method POST; 客户端的GET请求也会被转发成POST

proxy_hide_header

Nginx会将上游服务器的响应转发给客户端,但默认不会转发以下HTTP头部字段:Date、Server、X-Pad和X-Accel-*.使用proxy_hide_header可以指定哪些不能转发

proxy_hide_header Cache-Control;

proxy_pass_header

将原来禁止转发的header设为转发

proxy_pass_request_body

proxy_pass_request_headers

prxoy_redirect

当上游返回响应是重定向或刷新请求(301,302),proxy_redirect 可以重设HTTP头部的location或refresh字段。

proxy_redirect http://localhost:8000/two/ http://frontend/one/;

对location字段的URI是http://localhost:8000/two/some/uri.实际转发给客户端的是http://frontend/one/;

可以使用ngx-http-core-module提供的变量来设置

proxy_redirect http://localhost:8000/ http://$host:$server_port/;

可以省略replacement参数的主机名部分,这时会用虚拟主机名称填充
proxy_redirect http://localhost:8000/two/ /one/;

使用default参数时,会按照proxy_pass配置项和所属的location配置项重组

location /one/ {
  proxy_pass http://upstream:port/two/;
  proxy_redirect default;
}
等于
location /one/ {
    proxy_pass http://upstream:port/two/;
    proxy_redirect http://upstream:port/two/ /one/;
}

proxy_next_upstream

当向一台上游转发请求出错时,继续换一台处理
(invaild_header 上游响应不合法)

上一篇 下一篇

猜你喜欢

热点阅读