您的位置:首页 > 运维架构 > 反向代理

Nginx--反向代理、负载均衡、缓存、fpm

2017-07-06 12:59 176 查看

Nginx反向代理

格式:
location  /uri {
rewrite
proxy_pass http://back_server:port/newuri; }

/uri --> /newuri


1. 注意匹配的是路径的话,反代也是路径

ngx_http_proxy_module模块:
server {
listen
server_name
location /forum/ {
proxy_pass http://192.16.3.7:80/; proxy_set_header Host $host;
proxy_set_header X-Real_ip $remote_addr;
}
}
**如果后面没有新的路径,则匹配时补齐forum。如果有新的路径,则使用新的路径**


2. 匹配的如果是文件类型

ngx_http_proxy_module模块:
server {
listen
server_name
location ~* \.(jpg|png|gif)$ {
proxy_pass http://192.16.3.7:80; proxy_set_header Host $host;//请求首部主机
proxy_set_header X-Real_ip $remote_addr;//请求客户端IP
}
}

**这个地方因为是匹配文件,不存在匹配路径的问题,所以代理的地址不能有路径**


注意:获取实际请求的客户端信息,要调整web服务器的日志格式 %{X-Real-ip}i

反向代理的缓存功能

ngx_http_proxy_module:实现反向代理及缓存功能

proxy_pass http://{SERVER_IP|UPSTREAM_NAME}/uri 
proxy_cache_path path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size] ;

proxy_cache zone_name;

proxy_cache_valid [code] time;
proxy_cache_method
proxy_cache_use_stale error timeout ...
proxy_cache_min_uses

proxy_cache_bypass string: 设置在何种情形下nginx将不从cache取数据的;
$cookie_nocache $arg_nocache  $http_authorization

proxy_set_header


例子

在http段:
proxy_cache_path /cache/nginx/ levels=1:1:1 keys_zone=mycache:32m;
在server的location中:
proxy_cache mycache;
proxy_cache_valid 200 1d;
proxy_cache_valid any 1m;


Nginx的upstream

upstream backend {

#ip_hash;
server 192.168.1.251;
server 192.168.1.252;
server 192.168.1.247;

}
server {
listen       80;
server_name  trffweb;

location / {
#反向代理的地址
proxy_pass http://backend; }
}


负载均衡其他的问题

调度策略 ip_hash,least_conn,stick

**基于sticky实现session绑定:(保证如果都是反向代理,不会都代理到同一个后端)**
cookie
route
learn ()
例子:
upstream backend {
server backend1.example.com;
server backend2.example.com;

sticky cookie srv_id expires=1h domain=.example.com path=/;
}
least_conn: 调度方法,最少连接;

keepalive:后端如果是memcached,可以长链接

upstream memcached_backend {
server 127.0.0.1:11211;
server 10.0.0.2:11211;

keepalive 32;
}

server {
...

location /memcached/ {
set $memcached_key $uri;
memcached_pass memcached_backend;
}

health_check;
建议:关闭访问日志;
在http段:
math welcom{
status 200;
header Content-Type = text/html;
body ~ "Welcome to nginx!"
}
在location段
health_check math = welcome;

自定义响应首部:
add_header X-Via $server_addr;
add_header X-Cache $upstream_cache_status;


一致性Hash算法

当进行负载均衡后端代理时,针对缓存机制,对url取模,用一致性hash。

一致性hash算法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nginx hash
相关文章推荐