接着上次总结的nginx的反向代理继续总结。
总的upstream的配置方法一共有如下几种
官方网址: http://nginx.org/en/docs/http/ngx_http_upstream_module.html
根据官网上的介绍,upstream模块的样例配置。
upstream backend {
server nginx-2 weight=5;
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3;
server nginx-3 backup;
}
weight是权重, max_fails代表失败三次就被设置为失效,当到默认时间已过,才会被重新设置为有效。
fail_timeout是指超过30s未响应就是失败
基于ip地址的负载均衡,类似于LVS的sh。
upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
server backend3.example.com down;
}
比ip_hash更高级的基于cookie的负载均衡。
sticky需要提前配置 装nginx-sticky-module-1.1.tar.gz
upstream backend {
server nginx-2;
server nginx-3;
sticky cookie srv_id expires=1h domain=.nginx.lol path=/;
}
方法二:基于route的
map $cookie_jsessionid $route_cookie {
~.+\.(?P\w+)$ $route;
}
map $request_uri $route_uri {
~jsessionid=.+\.(?P\w+)$ $route;
}
upstream backend {
server backend1.example.com route=a;
server backend2.example.com route=b;
sticky route $route_cookie $route_uri;
}
观察upstream中的命中状态。
在server中添加add_header
add_header X-Via $server_addr;
add_header X-Cache $upstream_cache_status;
这样的话。返回给客户端的响应报文会多两个字段
[root@example1 nginx]# curl -I nginx-1/forum/ubuntu.jpg
HTTP/1.1 200 OK
Server: nginx/1.12.0
Date: Tue, 06 Jun 2017 08:53:20 GMT
Content-Type: image/jpeg
Content-Length: 527050
Connection: keep-alive
Last-Modified: Sat, 24 Dec 2016 06:47:37 GMT
ETag: "585e1a09-80aca"
X-Via: 192.168.30.137
X-Cache: HIT
Accept-Ranges: bytes
可以写fast-cgi的反向代理。是为了向后端代理PHP之类的动态语言。
首先要安装php-fpm,并启动php-fpm。使之监听在9000端口上。
再更改/etc/nginx/fastcgi_params。因为默认的配置文件不支持。
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
同样fastcgi的运行内容也可以去缓存。
在http中定义
...
proxy_cache_path /cache/nginx/ levels=1:2 max_size=20m inactive=5m keys_zone=mycache:32m;
fastcgi_cache_path /cache/fastcgi/ levels=1:2 max_size=1g inactive=10m keys_zone=fcgicache:10m;
...
在location中定义。
location ~ \.php$ {
fastcgi_cache fcgicache;
fastcgi_pass nginx-2:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
}
nginx的fastcgi还可以去做一些限制,如fastcgi_limit_rate。