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

Nginx的反向代理,负载均衡,缓存,URL重写以及读写分离

2017-03-24 20:33 489 查看

Nginx.conf

             这里主要讲解一下nginx的主配置文件nginx.conf。其中主要分为四个部分:main(全局配置)、server(主机配置)、upstream(上游服务器,主要为反向代理、负载均衡的相关配置)和location(可以正则匹配)

(main)全局配置是设置影响全局配置的指令的。定义有

日志位置,

执行的用户,

worker进程的数量。一般来说是cpu的核数。

worker_cpu_affinity设置CPU,在高并发的情况下设置cpu的粘性来降低由于多CPU核切换造成的寄存器等现场重建带来的性能损耗。

use epoll,设置Linux的epoll的IO模型。

http服务器相关。

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
use epoll
worker_connections  1024;
}


看看监听在80端口的进程与用户。

[root@web2 html]# lsof -i :80
COMMAND  PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   1263  root    6u  IPv4  13016      0t0  TCP *:http (LISTEN)
nginx   1265 nginx    6u  IPv4  13016      0t0  TCP *:http (LISTEN)
[root@web2 html]#
http服务器。

include  /etc/nginx/mime.types;     设定mime类型。

sendfile on  开启高效文件传输模式。

keepalive_timeout 60  长连接超时时间。

send_timeout 指定客户端的超时时间。

tcp_nopush   不做推送  结合nagle算法,不着急发数据,等数据积攒多点再发

tcp_nodelay  不做等待  有数据不等待,直接就发送

gzip on 压缩传输开启

client_max_body_size  10m  允许客户端的最大文件字节数

http {
include       mime.types;
default_type  application/octet-stream;

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;
server { } 定义虚拟主机

server {
listen       80;
server_name  localhost;

#charset koi8-r;

#access_log  logs/host.access.log  main;

location / {
root   html;
index  index.php index.html index.htm;
}

反向代理(将访问的forum内容转到12的forum)

location /forum {
proxy_pass http://192.168.217.12:80/forum; }
所有的访问 以/fprum开头的都做反向代理。但是封装一个真实客户端的IP地址。

location * ^/forum {
proxy_pass http://192.168.217.12; proxy_set_header X-Real-IP $remote_addr;
}
将访问全部代理到后台去。

location / {
proxy_pass http://192.168.217.12/; proxy_set_header X-Real-IP $remote_addr;
}
配置一个组的反向代理并且附带健康检查(必须定义在server外面)(upstream模块加入,将反向代理定义成了一个组,所以在location那里直接可以根据正则反向代理)

upstream realserver {
server 192.168.217.11:80 weight=1 max_fails=2 fail_timeout=2;
server 192.168.217.12:80 weight=1 max_fails=2 fail_timeout=2;
}
server {
listen       80;
server_name  localhost;
location / {
proxy_pass http://realserver/; proxy_set_header X-Real-IP $remote_addr;
}


负载均衡

通过该方法将提供不同功能的服务器区分开。php的专门有个组,图片的专门有个组。

upstream phpserver {
server1;
server2;
}

upstream imgsrvs {
server3;
server4;
}

location ~* \.php$ {
fastcgi_pass http://phpsrvs; }

location ~* "\.(jpg|jpeg|gif|png)$" {
proxy_pass http://imgsrvs; }


统计一下访问nginx的ip排名的主机。可以使用awk来进行。
[root@web2 nginx]# cat /var/log/nginx/access.log |awk -F" " '{ip[$1]++} END{for(i in ip){printf "%s%+10s\n",i,ip[i]}}'
127.0.0.1         1
192.168.217.1        78
192.168.217.10        25
192.168.217.131       110

然后排序就好。

[root@web2 nginx]# cat /var/log/nginx/access.log |awk -F" " '{ip[$1]++} END{for(i in ip){printf "%s%+10s\n",i,ip[i]}}'|sort -k2 -rn
192.168.217.131       110
192.168.217.1        78
192.168.217.10        25
127.0.0.1         1


设置缓存。

proxy_cache_path /nginx/cache/first levels=1:2 keys_zone=first:20m max_size=1g;

server {
listen       80;
server_name  localhost;
location / {
proxy_pass http://realserver/; proxy_set_header X-Real-IP $remote_addr;
proxy_cache first;
proxy_cache_valid 200 10m;
}

proxy_cahce:设置高速缓存的路径和其他参数,缓存数据存储在文件中。

levels = levels:设置缓存目录的层数,如levels=1:2 表示的是创建两层目录缓存,最多创建三层。

keys_zone=first:20m 为共享内存起个名字。

max_size=1g 最大容量。

在location 中定义谁去使用这些缓存

proxy_cache firsh;    使用缓存first

proxy_cache_valid 200 10m;   设置缓存的响应代码为200的缓存10分钟。

[root@web2 nginx]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: [emerg] mkdir() "/nginx/cache/first" failed (2: No such file or directory)
nginx: configuration file /etc/nginx/nginx.conf test failed
[root@web2 nginx]# mkdir -pv /nginx/cache/first
mkdir: created directory `/nginx'
mkdir: created directory `/nginx/cache'
mkdir: created directory `/nginx/cache/first'
创建目录后查看nginx的缓存文件。

[root@web2 nginx]# tree .
.
└── cache
└── first
├── 1
│   └── bf
│       └── 5cdae18ec79d104f95aa394163431bf1
└── 2
└── 3b
└── 7b14020849ae34e40fefcb6a7daf03b2

6 directories, 2 files

给客户端显示是谁提供的缓存,还有是否命中缓存。

[root@localhost ~]# curl -I 192.168.217.13
HTTP/1.1 200 OK
Server: nginx/1.4.2
Date: Fri, 17 Mar 2017 05:55:33 GMT
Content-Type: text/html
Content-Length: 66
Connection: keep-alive
Last-Modified: Wed, 15 Mar 2017 05:14:05 GMT
ETag: "42-54abe0369ce83"
Accept-Ranges: bytes
X-Via: 192.168.217.13     ##这里有显示
X-Cache: EXPIRED          ##这时缓存过期了,命中时是HIT
或者直接这么写。

server {
listen       80;
server_name  localhost;
add_header X-Cache "$upstream_cache_status from $server_addr";
location / {
proxy_pass http://realserver/; proxy_set_header X-Real-IP $remote_addr;
proxy_cache first;
proxy_cache_valid 200 10m;
}
访问后的显示。

[root@localhost ~]# curl -I 192.168.217.13
HTTP/1.1 200 OK
Server: nginx/1.4.2
Date: Fri, 17 Mar 2017 06:01:37 GMT
Content-Type: text/html
Content-Length: 66
Connection: keep-alive
Last-Modified: Wed, 15 Mar 2017 05:14:05 GMT
ETag: "42-54abe0369ce83"
X-Cache: HIT from 192.168.217.13
Accept-Ranges: bytes


URL重写

这个模块需要使用PCRE库。
比如访问浏览器地址http://192.168.217.12/bbs/index.html会自动跳转到http://192.168.217.11/forum/index.html
这里的$1表示的是前面的(.*)
location / {
root html;
index index.html index.htm;
rewrite ^/bbs/(.*)$ http://192.168.217.11/forum/$1; }

访问的结果是。
[root@localhost ~]# curl -I 192.168.217.13/bbs/index.html
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.4.2
Date: Sat, 18 Mar 2017 04:43:22 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://192.168.217.12/forum/index.html


302临时重定向(通常来说,定义到其他主机上就是临时重定向,转到本机上就是永久重定向。但是主要还是用redirect,permanent定义的是永久重定向还是临时重定向)

基本的指令有:
1.break
用于server,location,if
定义当前的设置的规则,停止执行其他的重写指令。直接响应资源(是为了防止循环的)
2.if
用于server,location。
一、~* 和~的正则表达式。
二、=和!=的比较语句。
三、~*不区分大小写。~是区分大小写。
四、使用 -f 检查一个文件是否存在。
五、使用-d检查一个目录是否存在。
六、使用-e检查一个文件,目录,软连接是否存在。
七、使用-x检查一个文件是否为可执行文件。
3.return
在结束执行的时候返回一个状态码。   可以使用以下的值如204,400,402-406,408等等。
4.rewrite
url的重写(其中有几个重要的尾部标记)
last:--完成重写指令,之后搜索相应的uri的location(看有没有再重定向)
break: --完成重写指令。(直接返回资源)
redirect:--返回302的临时重定向。
permanent:--返回301的永久重定向。

实现读写分离

location / {
proxy_pass http://192.168.217.11/; if ($request_method = "PUT") {
proxy_pass http://192.168.217.12; }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐