Nginx-web服务器和反向代理总结

一、Nginx管理

1.1、Nginx介绍

  • Nginx(engine x)是一款由俄罗斯的程序设计师lgor Sysoev所开发高性能的Web和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器。
  • 延伸版本tengine(淘宝研发)、openresty(章亦春)
  • 官网:http://nginx.org
  • 中文文档:http://www.nginx.cn/doc/index.html

1.2、Nginx安装、启动

yum -y install gcc pcre-devel zlib zlib-devel

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bfXR0Lhy-1675915308584)(Nginx-web服务器和反向代理学习.assets/image-20221112175451765.png)]

1.Nginx获取
  • 官网源码包
  • wget http://nginx.org/download/nginx-1.15.5.tar.gz -P /usr/src
2.配置
  • ./configure --prefix={installdir}
3.编译
  • make
4.安装
  • make install
5.启动
  • {installdir}/sbin/nginx
6.测试验证

elinks http://192.168.204.3 --dump

1.3、Nginx相关目录及配置文件详解

[root@xiongbinbin /]# cat /etc/nginx/nginx.conf# 启动子进程程序默认用户
user  nginx;
# 一个主进程和多个工作进程。工作进程是单进程的,且不需要特殊授权即可运行;这里定义的是工作进程的数量,默认是一个工作进程(子进程);
worker_processes  auto;# 全局错误日志的位置及日志格式
error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;events {# 每个工作进程最大的并发数,即线程数worker_connections  1024;
}# http服务器设置
http {# 设定mime类型,类型有mime.type文件定义include       /etc/nginx/mime.types;default_type  application/octet-stream;# 日志格式:log_format  格式名字:main   日志的内容包含什么。。。log_format  main  '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';# $remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;# $remote_user 用来记录客户端用户名称;# $time_local 用来记录访问的时间与时区;# $request 用来记录请求url与http协议;# $status 用来记录请求状态;成功是200;# $body_bytes_sent 记录发送给客户端文件主题内容的大小;# $http_referer 用来记录从哪个页面链接访问过来的;# $http_user_agent 记录客户端浏览器的相关信息,例如:浏览器,手机客户端等;# 全局访问日志的路径,采用的格式是上面定义的main日志格式access_log  /var/log/nginx/access.log  main;#sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为on#sendfile = off 时,应用程序读取磁盘中的文件以字节流的形式从磁盘中加载文件,然后再将文件以字节流的形式复制到内核中。内核在把文件推送到NC。#sendfile = on 时,应用程序直接向内核发送指令,让内核去读文件。读完文件内核直接推送给NC。只有一次复制操作,实现异步网络IO形式。因此,性能会有很大的提升。sendfile        on;# 此选项允许或禁止使用socke的TCP_CORK的选项,此选项仅在使用sendfile的时候使用#tcp_nopush     on;# 长连接超时时间keepalive_timeout  65;# 开启压缩 #gzip  on;#这里指定的配置是server的配置,表示虚拟主机的配置include /etc/nginx/conf.d/*.conf;
}
============
server {# 虚拟主机使用的端口listen       80;# 虚拟主机域名server_name  localhost;# 虚拟主机的访问日志路径#access_log  /var/log/nginx/host.access.log  main;# 虚拟主机支撑的字符集charset koi8-r;# 定义web根路径location / {# 根目录路径root   /usr/share/nginx/html;# 索引页index  index.html index.htm;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html## 根据错误码 返回对应的页面error_page   500 502 503 504  /50x.html;location = /50x.html {root   /usr/share/nginx/html;}# 定义反向代理服务器 数据服务器是lamp模型# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {#    proxy_pass   http://127.0.0.1;#}# 定义PHP为本机服务的模型# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##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;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one## 拒绝apache DR目录及子目录下的.htaccess文件访问#location ~ /\.ht {#    deny  all;#}
}
1、Nginx默认网站
  • 当Nginx配置文件中有且只有一个Server的时候,该Server就被Nginx认为是默认网站,所有发给Nginx服务器80端口的数据都会默认给该Server.
server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;# Nginx的默认网站设置location / {# root目录设置root   /usr/share/nginx/html;# 静态资源文件index  index.html index.htm;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   /usr/share/nginx/html;}}
2、Nginx目录访问控制
server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;# location / {root   /usr/share/nginx/html;index  index.html index.htm;}# 访问控制 只允许本机访问 a 目录 其他机器拒绝访问location /a {root   /usr/share/nginx/html;index  index.html index.htm;# allow  deny 设置允许和拒绝访问的限制# 这里设置为允许本机127.0.0.1访问,拒绝其他主机访问allow 127.0.0.1;deny all;# return 可以控制返回给客户端的信息,可以返回错误码等;# 还可以返回图片(链接形式)或指定链接# return 404;# return 502;# return www.baidu.com}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   /usr/share/nginx/html;}}
3、Nginx登录验证
  • 需要借助htpasswd命令:

    • 安装:yum -y install httpd-tools

      • htpasswd -cmb /etc/nginx/htpasswd sko 123456
    • usage:
      • htpasswd -b[cmBdpsDv] [-C cost] passwordfile username password
server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;# Nginx的默认网站设置location / {# root目录设置root   /usr/share/nginx/html;# 静态资源文件index  index.html index.htm;}# 目录验证:任何人都可以访问,但是需凭用户密码才能访问location /b {# root目录设置root   /usr/share/nginx/html;# 静态资源文件index  index.html index.htm;auth_basic "test登录验证 123456";auth_basic_user_file /etc/nginx/htpasswd;}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   /usr/share/nginx/html;}}
  • **配置重新加载生效:killall -s HUP nginx **
4、日志格式
  • Nginx访问日志主要有两个参数控制

    • log_format : 用来定义记录日志的格式(可以定义多种日志格式,取不同名字即可)

      • log_format log_name ‘string’ ; # string 指的是日志字段集,可参考1.3
    • access_log # 用来指定日志文件的路径及使用的何种日志格式记录日志
      • access_log logs/access.log log_name; 示例可参考1.3
    user  nginx;
    worker_processes  auto;error_log  /var/log/nginx/error.log notice;
    pid        /var/run/nginx.pid;events {worker_connections  1024;
    }http {include       /etc/nginx/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"';log_format  test_01 '$time_local - $remote_addr "$request" $status';log_format  main_json '{"@timestamp":"$time_local",''"client_ip":"$remote_addr",''"request":"$request",''"status":"$status",''"bytes":"$body_bytes_sent",''"x_forwarded":"$http_x_forwarded_for",''"referer":"$http_referer",''}';access_log  /var/log/nginx/access.log  main_json;sendfile        on;#tcp_nopush     on;keepalive_timeout  65;#gzip  on;include /etc/nginx/conf.d/*.conf;
    }
    test_01格式:
    13/Nov/2022:14:17:06 +0800 - 192.168.204.1 "GET /b/ HTTP/1.1" 304
    13/Nov/2022:14:17:08 +0800 - 192.168.204.1 "GET /b/ HTTP/1.1" 304
    13/Nov/2022:14:17:08 +0800 - 192.168.204.1 "GET /b/ HTTP/1.1" 304
    13/Nov/2022:14:17:08 +0800 - 192.168.204.1 "GET /b/ HTTP/1.1" 304
    13/Nov/2022:14:17:08 +0800 - 192.168.204.1 "GET /b/ HTTP/1.1" 304main_json格式:
    {"@timestamp":"13/Nov/2022:14:18:29 +0800","client_ip":"192.168.204.1","request":"GET /b/ HTTP/1.1","status":"304","bytes":"0","x_forwarded":"-","referer":"-",}
    {"@timestamp":"13/Nov/2022:14:18:30 +0800","client_ip":"192.168.204.1","request":"GET /b/ HTTP/1.1","status":"304","bytes":"0","x_forwarded":"-","referer":"-",}
    {"@timestamp":"13/Nov/2022:14:18:30 +0800","client_ip":"192.168.204.1","request":"GET /b/ HTTP/1.1","status":"304","bytes":"0","x_forwarded":"-","referer":"-",}
5、防盗链
  • Nginx防盗链的具体实现:

    • valid_referers : nginx会通过查看referer自动和valid_referers后面的内容进行匹配,如果匹配到了就将invalid_referer变 量 置 0 ,如果没有匹配到,则将invalid_referer变量置为1,匹配的过程中不区分大小写。
    参数说明:none: 如果请求Header中的Referer为空,说明没有盗链,允许访问blocked:在Header中的Referer不为空,但是该值被防火墙或代理进行伪装过,如不带"http://" 、"https://"等协议头的资源允许访问。server_names:指定具体的域名或者IPstring: 可以支持正则表达式和*的字符串。如果是正则表达式,需要以~开头表示,例:location ~*\.(png|jpg|gif){valid_referers none blocked www.baidu.com 192.168.200.222 *.example.com example.*  www.example.org  ~\.google\.;if ($invalid_referer){return 403;}root /usr/local/nginx/html;}
server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;# Nginx的默认网站设置location / {# root目录设置root   /usr/share/nginx/html;# 静态资源文件index  index.html index.htm;}location /c {# root目录设置root   /usr/share/nginx/html;# 静态资源文件index  index.html index.htm;# valid_referers none blocked *.ayitula.com;if ($invalid_referer) {return 403;}}#error_page  404              /404.html;# redirect server error pages to the static page /50x.html#error_page   500 502 503 504  /50x.html;location = /50x.html {root   /usr/share/nginx/html;}}

1.5、Nginx虚拟主机

1、虚拟主机介绍
  • 一个Web服务器软件默认情况下只能发布一个web,因为一个Web分享出去需要三个条件(IP、Port、Domain name)
  • 一个Web服务器软件如何发布多个Web?
  • 虚拟主机:就是把一台服务器划分成多个虚拟的服务器,每一个虚拟主机都可以有独立的域名和独立的目录。
2、基于IP的虚拟主机
  • 特点:每一个网站都需要一个IP
  • 缺点:需要多个IP,如果是公网IP ,就需要付费
同时发布两个网站:- DocumentRoot  /usr/share/nginx/html/web1- DocumentRoot    /usr/share/nginx/html/web2步骤1:创建虚拟主机
ifconfig ens33:1 192.168.204.4/24 up步骤2:创建对应静态资源文件/usr/share/nginx/html/web1/usr/share/nginx/html/web2echo web01 > /usr/share/nginx/html/web1/index.htmlecho web02 > /usr/share/nginx/html/web2/index.html步骤3:修改配置文件
server {listen  192.168.204.3:80;location / {root   /usr/share/nginx/html/web1/;index   index.html index.htm;}
}server {listen 192.168.204.4:80;location / {root   /usr/share/nginx/html/web2;index    index.html index.htm;}
}步骤4:重启Nginx,并查看启动成功
[root@xiongbinbin conf.d]# netstat -ntpl |grep 80
tcp        0      0 192.168.204.4:80        0.0.0.0:*               LISTEN      5640/nginx: master
tcp        0      0 192.168.204.3:80        0.0.0.0:*               LISTEN      5640/nginx: master
tcp        0      0 127.0.0.1:6010          0.0.0.0:*               LISTEN      1805/sshd: root@pts
tcp6       0      0 ::1:6010                :::*                    LISTEN      1805/sshd: root@pts步骤5: 验证
[root@xiongbinbin conf.d]# elinks http://192.168.204.3 --dumpweb01
[root@xiongbinbin conf.d]# elinks http://192.168.204.4 --dumpweb02
3、基于端口的虚拟机
  • 特点:只需要一个IP
  • 缺点:端口你是无法告诉公网用户,所以无法适用于公网客户,适合内部用户
先停掉上面步骤启动的网卡ens33:1  ifconfig ens33:1 down步骤1: 修改配置文件
server {listen  80;location / {root /usr/share/nginx/html/web1/;index   index.html index.htm;}
}server {listen 8080;location / {root   /usr/share/nginx/html/web2;index    index.html index.htm;}
}步骤2: 重启Nginx,检查启动结果
lsof -i:80
lsof -i:8080步骤3:访问验证
[root@xiongbinbin html]# elinks http://192.168.204.3 --dumpweb01
[root@xiongbinbin html]#
[root@xiongbinbin html]#
[root@xiongbinbin html]# elinks http://192.168.204.3:8080 --dumpweb02
[root@xiongbinbin html]#
3、基于域名
  • 配置文件中添加域名映射:server_name 域名;

  • 可以解决1、2中的缺点,满足公网用户需求

  • 前提是主机要配置域名解析

前提:要配置域名解析
vim /etc/hosts127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.204.3 xiongbinbin
192.168.204.3 www.web1.com
192.168.204.3 www.web2.com步骤1: 修改配置文件
server {listen     80;server_name  www.web1.com;charset utf-8;location / {root   /usr/share/nginx/html/web1;index  index.html index.htm;}
}
server {listen      80;server_name  www.web2.com;charset utf-8;location / {root   /usr/share/nginx/html/web2;index  index.html index.htm;}
}步骤2: 重启Nginx,检查启动结果
lsof -i:80步骤3:访问验证
[root@xiongbinbin html]# elinks http://www.web1.com --dumpweb01
[root@xiongbinbin html]#
[root@xiongbinbin html]#
[root@xiongbinbin html]# elinks http://www.web2.com --dumpweb02
[root@xiongbinbin html]#

1.6、反向代理

1、代理介绍
  • 代理服务器,客户机在发送请求时,不会直接发送给目的主机,而是先发送给代理服务器,代理服务器接受客户机请求之后,再向主机发出,并接收目的主机返回的数据,存放在代理服务器的硬盘中,再发送给客户机。
2、应用场景:
  • 堡垒机场景

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OtPH02id-1675915308585)(Nginx-web服务器和反向代理学习.assets/image-20221113163256154.png)]

  • 内网服务器发布场景

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oPnHB45t-1675915308585)(Nginx-web服务器和反向代理学习.assets/image-20221113163500687.png)]

  • 缓存场景

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QHVk24Ux-1675915308586)(Nginx-web服务器和反向代理学习.assets/image-20221113163843780.png)]

3、反向代理原理
4、反向代理实现
proxy_pass:   nginx反向代理指令反向代理实现
location / {index index.html index.htm;   #定义首页索引文件的名称proxy_pass  http://mysvr;#请求转向mysvr 定义的服务器列表
5、反向代理优化
server {listen     80;server_name  www.web1.com;charset utf-8;location / {index  index.html index.htm;proxy_pass  http://mysvr;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;client_max_body_size 10m;client_body_buffer_size 128k;proxy_connect_timeout 90;proxy_send_timeout 90;proxy_read_timeout 90;proxy_buffer_size 4k;proxy_buffers 4 32k;proxy_busy_buffers_size 64k;proxy_temp_file_write_size 64k; }
}proxy_set_header Host $host; #修改请求头,添加Host字段
proxy_set_header X-Real-IP $remote_addr;#修改请求头,添加X-Real-IP字段
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#修改请求头,添加X-Forwarded-For字段
client_max_body_size 10m;#允许客户端请求的最大单文件字节数
client_body_buffer_size 128k;#缓冲区代理缓冲用户端请求的最大字节数,
proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout 90;#后端服务器数据回传时间(代理发送超时)
proxy_read_timeout 90;#连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size 4k;#设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers 4 32k;#proxy_buffers缓冲区,网页平均在32k以下的话,这样设置proxy_busy_buffers_size 64k;#高负荷下缓冲大小(proxy_buffers*2)
proxy_temp_file_write_size 64k;#设定缓存文件夹大小,大于这个值,将从upstream服务器传

1.7、Nginx下载限速

1、限速目的
  • 限速该特性可以限制某个用户在一个给定时间段内能够产生的HTTP请求数。请求可以简单到就是一个对于主页的GET请求或者一个登录表格的POST请求。

  • 限速也可以用于安全目的上,比如暴力密码破解攻击,通过限制进来的请求速率,并且(结合日志)标记除目标URLS来帮助防范DDOS攻击。一般地说,限流是用在保护上游应用服务器不被在同一时刻的大量用户请求湮没。

2、应用场景
  • DDOS防御
  • 下载场景保护IO
3、限速原理
  • 算法思想:水(请求)从上方倒入水桶,从水桶下方流出(被处理);来不及流出的水存在水桶中(缓冲),以固定速率流出;水桶满后溢出(丢弃)。
  • 算法的核心:缓存请求,匀速处理、多余的请求直接丢弃。
4、实现方式
  • Nginx官方版本限制IP的连接数和并发分别有两个模块;

    • limit_req_zone 用来限制单位时间内的请求数,即速率限制。
    • limit_conn_zone 用来限制同一时间连接数,即并发限制。
限速案例一:
基于IP对现在速率做限制 限制每秒处理一次请求,对突发超过5个以后的请求放入缓存区。http {limit_req_zone $binary_remort_addr zone=test123:10m rate=1r/s;server {location /search/ {limit_req zone=test123 burst=5 nodelay;}}
}limit_req_zone $binary_remort_addr zone=test123:10m rate=1r/s;
第一个参数: $binary_remort_addr 表示通过remote_addr这个标识来做限制,"binary_"的目的是缩写内存占用量,是限制同一客户端ip地址。
第二个参数: zone-test123:10m 表示生成一个大小为10M,名字为test123的内存区域,用来存储访问频次信息。
第三个参数: rate=1r/s 表示允许相同标识的客户端的访问频次,这里限制的是每秒1次,即每秒只处理一个请求,还可以有比如30r/m的,即限制每2秒访问一次,即每2秒才处理一个请求。limit_req zone=test123 burst=5 nodelay;zone=test123 :设置使用哪个配置区域来做限制,与上面limit_req_zone 里的name对应。burst=5 : 重点说明一下这个配置,burst爆发的意思,这个配置的意思是设置一个大小为5的缓冲区当有大量请求(爆发)过来时,超过了访问频次限制的请求可以先放到这个缓冲区内等待,但是这个等待区里的位置只有5个,超过的请求会直接报503的错误然后返回。nodelay:如果设置,会在瞬时提供处理(burst + rate)个请求的能力,请求超过(burst + rate)的时候就会直接返回503,永远不存在请求需要等待的情况。(这里的rate的单位是:r/s)如果没有设置,则所有请求会依次等待排队。
  • 实战演示
limit_req_zone $binary_remote_addr zone=test123:10m rate=1r/s;
server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;location / {root   /usr/share/nginx/html;index  index.html index.htm;}location /search {root   /usr/share/nginx/html;index  index.html index.htm;limit_req zone=test123 burst=5 nodelay;}
[root@xiongbinbin conf.d]# elinks http://192.168.204.3/search --dump限速测试
[root@xiongbinbin conf.d]#
[root@xiongbinbin conf.d]#
[root@xiongbinbin conf.d]# elinks http://192.168.204.3/search --dump限速测试
[root@xiongbinbin conf.d]# elinks http://192.168.204.3/search --dump限速测试
[root@xiongbinbin conf.d]#
[root@xiongbinbin conf.d]# elinks http://192.168.204.3/search --dump限速测试
[root@xiongbinbin conf.d]#
[root@xiongbinbin conf.d]# elinks http://192.168.204.3/search --dumpAn error occurred.Sorry, the page you are looking for is currently unavailable.Please try again later.If you are the system administrator of this resource then you should checkthe error log for details.Faithfully yours, nginx.
[root@xiongbinbin conf.d]#
限速案例二:
基于IP做连接限制  限制同一IP并发为1  下载速度为100klimit_conn_zone $binary_remote_addr zone=addr:10m;
server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;location / {root   /usr/share/nginx/html;index  index.html index.htm;}location /load {root   /usr/share/nginx/html;index  index.html index.htm;limit_conn addr 1; # 限制同一个ip连接数limit_rate 100k; # 限制下载速度}

1.8、URL重写

1、URL rewrite介绍
  • rewrite模块 (nginx_http_rewrite_module)

  • Rewrite功能是Nginx服务器提供的一个重要功能。几乎是所有的web产品必备技能,用于实现URL重写。URL重写是非常有用的功能,比如它可以在我们改变网站结构后,不需要客户端修改原来的书签,也不需要其他网站修改我们网站的友情链接,还可以在一定程度上提高网站的安全性,能够让我们的网站显得更专业。

  • Nginx服务器Rewrite功能的实现是依赖于PCRE(Perl Compatible Regular Expression. Perl兼容的正则表达式)的支持,所以在编译安装Nginx之前,需要安装PCRE库。

2、应用场景
  • 域名变更
  • 用户跳转(从某个连接跳转到另一个连接)
  • 伪静态场景(便于CDN缓存动态页面数据)
3、URL重写原理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NUThPLHb-1675915308586)(Nginx-web服务器和反向代理学习.assets/image-20221114103203648.png)]

4、URL 重写实现
1、URL语法模块
1)set        设置变量
2)if        负责语句中的判断
3)return    返回返回值或URL
4)break     终止后续的rewrite规则
5)rewrite   重定向URL
2、Rewrite规则相关命令–set指令
  • 作用域:server、location、if
set指令    自定义变量
Syntax:
set $variable value;
Default:
_Context(作用域): server,location,if# 将http://www.ayitula.com 重写为 http://www.ayitula.com/baism
location / {set $name test123;rewrite ^(.*)$ http://www.baidu.com/$name;
}
  • 示例
1、set 指令重写server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;location / {#root   /usr/share/nginx/html;#index  index.html index.htm;# set 指令重写set $name test123;rewrite ^(.*)$ http://www.baidu.com/$name;}
}[root@xiongbinbin ~]# elinks http://192.168.204.3 --dumpNot FoundThe requested URL /test123 was not found on this server.
[root@xiongbinbin ~]#
3、Rewrite规则相关命令–if指令
  • 作用域:server、location
if 指令 负责判断模糊匹配 : ~ : 匹配!~ : 不匹配~* : 不区分大小写的匹配精确匹配 := 、~=
Syntax:
if(condition){...}
Default:
_
Context: server,locationlocation / {root html;index index.html index.htm;if ($http_user_agent ~* 'chrome') {break;# return 403;# return http://www.baidu.com;}
}
  • 示例
server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;location / {root   /usr/share/nginx/html;index  index.html index.htm;#set $name test123;#rewrite ^(.*)$ http://www.baidu.com/$name;if ($http_user_agent ~* 'chrome') {return 403;}}
}
  • 谷歌浏览器访问

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8rj5PdOJ-1675915308586)(Nginx-web服务器和反向代理学习.assets/image-20221114111648828.png)]

  • IE浏览器访问

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Mup874Ws-1675915308586)(Nginx-web服务器和反向代理学习.assets/image-20221114111753807.png)]

4、Rewrite规则相关命令–return指令
  • return:code/text/url

    • 可以返回:错误码、文本、URL
  • 作用域:server、location、if

Syntax: return code/text;
return code URL;
return URL;
Default: -
Context: server,location,iflocation / {root html;index index.html index.htm;if ($http_user_agent ~* 'chrome') {# return 403;return http://www.baidu.com}
}
  • 示例
server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;location / {root   /usr/share/nginx/html;index  index.html index.htm;#set $name test123;#rewrite ^(.*)$ http://www.baidu.com/$name;if ($http_user_agent ~* 'chrome') {#break;#return 403;return http://www.baidu.com;}}
}
5、Rewrite规则相关命令–break指令
  • break 指令 停止执行当前虚拟主机的后续rewrite指令集
  • 作用域:server、location、if
Syntax: break;
Default: -
Context: server,location,iflocation / {root html;index index.html index.htm;if ($http_user_agent ~* 'chrome') {break;return http://www.baidu.com}
}
  • 示例
server {listen       80;server_name  localhost;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;location / {root   /usr/share/nginx/html;index  index.html index.htm;#set $name test123;#rewrite ^(.*)$ http://www.baidu.com/$name;if ($http_user_agent ~* 'chrome') {break;return http://www.baidu.com;}}
}
6、Rewrite规则相关命令–rewrite指令
  • 语法
rewrite  <regex> <replacement> [flag];关键字    正则     替代内容    flag标记flag:redirect  # 返回302临时重定向,浏览器地址会显示跳转后的URL地址;permanent  # 返回301永久重定向,浏览器地址栏会显示跳转后的URL地址;last      # 本条规则匹配完成后,继续向下匹配新的location URL规则break      # 本条规则匹配完成即终止,不再匹配后面的任何规则,类似redirect,客户端状态码返回302;
域名跳转
www.baidu.com  重写为 www.jd.comserver {listen       80;server_name  www.baidu.com;charset utf-8;#access_log  /var/log/nginx/host.access.log  main;location / {rewrite ^(.*)$ http://www.jd.com permanent;}
}注意:
重定向就是将网页自动转向重定向
301永久性重定向 : 新网址完全继承旧网址,旧网址的排名等完全清零301重定向是网页更改地址后对搜索引擎友好的最好方法,只要不是暂时搬移的情况,都建议使用301来做转让。
302临时性重定向 : 对旧网址没有影响,但新网址不会有排名搜索引擎会抓取新的内容而保留旧的网址。
  • 示例
server {listen     80;server_name  www.web1.com;charset utf-8;location / {root   /usr/share/nginx/html/web1;index  index.html index.htm;}
}
server {listen      80;server_name  www.web2.com;charset utf-8;location / {rewrite ^/$ http://www.web1.com permanent;}
}[root@xiongbinbin conf.d]# elinks http://www.web2.com --dumpweb01
[root@xiongbinbin conf.d]#
server {listen      80;server_name  www.web2.com;charset utf-8;location / {#rewrite ^/$ http://www.baidu.com redirect;#rewrite ^/$ http://www.baidu.com permanent;#rewrite ^/$ http://www.baidu.com break;}
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pv9zlIso-1675915308586)(Nginx-web服务器和反向代理学习.assets/image-20221114122419561.png)]

  • 这里重点讲一下flag : last

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7SeNFeuF-1675915308587)(Nginx-web服务器和反向代理学习.assets/image-20221114124132330.png)]

  • last应用

    • 根据用户浏览器重写访问目录
根据用户浏览器重写访问目录location / {....
if ($http_user_agent ~* 'chrome') {rewrite ^(.*)$ /chrome/$1 last;
}location /chrome {root html;index index.html;}
}
  • 示例
当使用谷歌浏览器访问URL : /rewrite 时,重写到/chrome/rewrite
准备静态资源
[root@xiongbinbin conf.d]# cat /usr/share/nginx/html/chrome/rewrite/index.html
rewrite testserver {listen      80;server_name  localhost;charset utf-8;location / {#rewrite ^/$ http://www.baidu.com redirect;#rewrite ^/$ http://www.baidu.com break;if ($http_user_agent ~* 'chrome') {rewrite ^(.*)$ /chrome/$1 last;}location /chrome {root /usr/share/nginx/html;index index.html index.htm;}}
}==============
谷歌浏览器访问http://192.168.204.3/rewrite/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bkzDu7Ab-1675915308587)(Nginx-web服务器和反向代理学习.assets/image-20221114142750103.png)]

二、Nginx优化

2.1 优化目的

  • 标准情况下,软件默认的参数都是对安装软件的硬件标准来设置的,目前我们服务器的硬件资源远远大于要求的标准,所以为了让服务器性能更加出众,充分利用服务器的硬件资源,我们一般需要优化APP的并发数来提升服务器的性能。

2.2 优化方案

1、Nginx是主进程+工作进程模型

  • worker_processes 1; 工作进程数量 按CPU的总核数调整

  • worker_cpu_affinity 0001 0010 0100 1000; CPU的亲和力

  • worker_connections 1024; 一个工作进程的并发数

1.查询主机的cpu核数,根据主机cpu情况进行设置工作进程数量
2.根据1调整CPU的亲和力,使每个核上都有进程
3.设置一个工作进程的并发数# 查看CPU核数:cat /proc/cpuinfo  |grep 'flags'|wc -l# 修改配置
user  nginx;
worker_processes  4;  #工作进程数量
worker_cpu_affinity  0001 0010 0100 1000; # CPU的亲和力error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;events {worker_connections  10240; # 一个工作进程的并发数
}# 重启后检查每个核上是否都能挂上进程
ps -eo psr,pid,args |grep 'nginx'

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-q1Hpeubw-1675915308587)(Nginx-web服务器和反向代理学习.assets/image-20221114152000584.png)]

2、长连接

  • http协议属于TCP协议
  • 优化目标:减少三次握手和四次挥手的次数
    • keepalive_timeout 5; 长连接的时间,单位秒;如果设置 0 秒就是将长连接关闭
    • keepalive_requests 8192; 每个长连接接受最大的请求数
user  nginx;
worker_processes  auto;error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;events {worker_connections  1024;
}http {include       /etc/nginx/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  /var/log/nginx/access.log  main;sendfile        on;#tcp_nopush     on;#keepalive_timeout  65;keepalive_timeout  0;  # 此例表示将长连接关闭,服务器返回数据后即关闭连接#keepalive_requests 8192;#gzip  on;include /etc/nginx/conf.d/*.conf;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f2B920nU-1675915308587)(Nginx-web服务器和反向代理学习.assets/image-20221114154545179.png)]

user  nginx;
worker_processes  auto;error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;events {worker_connections  1024;
}http {include       /etc/nginx/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  /var/log/nginx/access.log  main;sendfile        on;#tcp_nopush     on;#keepalive_timeout  65;keepalive_timeout  5;  # 此例表示将长连接保持5秒keepalive_requests 8192; # 同一个长连接最多接受请求数#gzip  on;include /etc/nginx/conf.d/*.conf;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-i1bu8Sx2-1675915308587)(Nginx-web服务器和反向代理学习.assets/image-20221114154736296.png)]

3、数据压缩

相关配置参数:
gzip on;
gzip_proxied any;
gzip_min_length 1k;
gzip_buffers 4 8k;
gzip_comp_level 6;
gzip_types text/plain text/css application/x-javascript application/javascript application/xml;配置参数说明:gzip off;          off/开启  on/关闭gzip_proxied any;      Nginx做前端代理时启用该选项,表示无论后端服务器的headers头返回什么信息,都无条件启用压缩gzip_min_length 1k;     启用gzip压缩的最小文件,小于设置值的文件将不压缩gzip_comp_level 6;     gzip压缩级别 1-9, 数字越大压缩的越好,也越占用CPU时间gzip_types text/plain text/css application/x-javascript application/javascript application/xml;     进行压缩的文件类型。类型可以在mime.types文件中找到gzip_vary on;     是否在http header中添加Vary:Accept-Encoding,建议开启gzip_disable "MSIE[1-6]\";      禁用IE 1-6 gzipgzip_buffers 32 4k;        设置压缩所需要的缓冲区大小gzip_http_verdion 1.0;     设置gzip压缩针对的HTTP协议的版本
  • 示例
user  nginx;
worker_processes  auto;error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;events {worker_connections  1024;
}http {include       /etc/nginx/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  /var/log/nginx/access.log  main;sendfile        on;#tcp_nopush     on;#keepalive_timeout  65;keepalive_timeout  5;keepalive_requests 8192;gzip on;gzip_proxied any;gzip_min_length 1k;gzip_buffers 4 8k;gzip_comp_level 6;gzip_types text/plain text/css application/x-javascript application/javascript application/xml;include /etc/nginx/conf.d/*.conf;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-i1xQ02QN-1675915308587)(Nginx-web服务器和反向代理学习.assets/image-20221114161747270.png)]

4、客户端缓存

server {listen      80;server_name  localhost;charset utf-8;location ~* \.(png|gif)$ {root /usr/share/nginx/html;index index.html index.htm;expires 1h;  # 这里设置缓存过期时间是1小时
}
}# 从图中可以看出1.png图片具有缓存时间1h,第一次是从服务器获取数据(状态码200),第二次请求是从缓存获取数据(状态码304)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WhX1Jwfm-1675915308588)(Nginx-web服务器和反向代理学习.assets/image-20221114163646287.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kkYmQVhO-1675915308588)(Nginx-web服务器和反向代理学习.assets/image-20221114163546424.png)]

三、Nginx负载均衡

3.1、集群介绍

第一种解释:将多个物理机器组成一个逻辑计算机,实现负载均衡和容错
第二种解释:计算机集群简称集群,是一种计算机系统,它通过一组松散集成的计算机软件或硬件连接起来高度紧密地协作完成计算工作。在某种意义上,他们可以被看做是一台计算机。
  • 传统web访问模型

    • 完成一次请求的步骤

      1. 用户发起请求
      2. 服务器接受请求
      3. 服务器处理请求(压力最大)
      4. 服务器响应请求
    • 缺点:单点故障
      1. 单台服务器资源有限
      2. 单台服务器处理耗时长
    • 单点故障解决方案
      1. 部署一台备份服务器,宕机直接切换
      2. 部署多台服务器,根据DNS的轮询解析机制去实现分发
    • 问题
      1. 方案1: 服务器利用率低,成本高,切换不及时,服务器压力依然大
      2. 方案2: 优势是用户处理速度得到了提升,但是当其中一台故障,就会有一部分用户访问不了网站
1、并行处理解决方案
  • 多机阵列—集群模式
  • 组成要素:
    1. VIP(虚ip) : 一个IP地址
    2. 分发器 : nginx
    3. 数据服务器 : Web服务器
2、Nginx集群原理
  • 在Nginx集群中Nginx扮演的角色是:分发器

  • 任务:接受请求、分发请求、响应请求

  • 功能模块:

    1. ngx_http_upstream_module:基于应用层(七层)分发模块
    2. ngx_stream_core_module:基于传输层(四层)分发模块
  • Nginx集群其实是:虚拟机+反向代理+upstream分发模块组成的

    • 虚拟主机:接受和相应请求
    • 反向代理:带用户去数据服务器拿数据
    • upstream:告诉Nginx去哪个数据服务器拿数据
  • 数据走向:

    1. 虚拟主机接受用户请求
    2. 虚拟主机去找反向代理
    3. 反向代理让去找upstream
    4. upstream 告诉一个数据服务器IP
    5. Nginx去找数据服务器 并发起用户的请求
    6. 数据服务器接受请求并处理请求
    7. 数据服务器响应请求给Nginx
    8. Nginx响应请求给用户

3.2、使用Nginx分发器构建一个WEB集群

  • 配置分发器
Syntax: upstream name {...}
Default: -
Context: http# upstream 模块
upstream web {server 192.168.204.3;
server 192.168.204.4;
}server {listen      80;server_name  localhost;charset utf-8;location / {proxy_pass http://web;
}
}

3.3、Nginx分发算法

  • Nginx的upstream模块目前支持4种方式的分配
  • Nginx业务服务器的状态
    1. down : 表示当前的server暂时不参与负载
    2. weight : 默认为1,weight越大,负载的权重就越大
    3. max_fails : 允许请求失败的次数,默认为1,当超过最大次数时,返回proxy_next_upstream 模块定义的错误
    4. fail_timeout : 失败超时时间,在连接Server时,如果在超时时间之内超过max_fails指定的失败次数,会认为fail_timeout时间内Server不可用,默认为10s
    5. backup : 其他所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻
3.3.1、默认算法
1、轮询(默认)
  • 每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
# 后端服务器server后不用状态标注的话,就是默认1:1轮询
http {upstream web {server 192.168.204.3;server 192.168.204.4;}server {listen      80;server_name  localhost;charset utf-8;location / {proxy_pass http://web;}}
}
2、基于权重的轮询(weight)
  • 指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
http {upstream web {server 192.168.204.3 weight=1;server 192.168.204.4 weight=2;}server {listen      80;server_name  localhost;charset utf-8;location / {proxy_pass http://web;}}
}
3、ip_hash
  • 每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
  • ip_hash不支持weight和backup
http {upstream web {ip_hash;server 192.168.204.3;server 192.168.204.4;}server {listen      80;server_name  localhost;charset utf-8;location / {proxy_pass http://web;}}
}
  • 业务服务器状态:down和backup应用示例
# down状态示例
http {upstream web {server 192.168.204.3 down; # 此时Nginx分发器不会分发请求到这台服务器server 192.168.204.4;}server {listen      80;server_name  localhost;charset utf-8;location / {proxy_pass http://web;}}
}# backup状态示例
http {upstream web {server 192.168.204.3;server 192.168.204.4 backup; # 当server1业务服务器忙不过来或者down掉时,才会分发请求到此台服务器}server {listen      80;server_name  localhost;charset utf-8;location / {proxy_pass http://web;}}
}
3.3.2、基于请求头的分发
1、基于host分发(即基于域名server_name)
http {upstream web1 {server 192.168.204.3;}upstream web2 {server 192.168.204.4;}server {listen      80;server_name  www.web1.com;charset utf-8;location / {proxy_pass http://web1;}}server {listen      80;server_name  www.web2.com;charset utf-8;location / {proxy_pass http://web2;}}
}
2、基于开发语言
http {upstream php {server 192.168.204.3;}upstream html {server 192.168.204.4;}server {listen      80;server_name  www.web1.com;charset utf-8;location ~* \.php$ {proxy_pass http://php;}location ~* \.html$ {proxy_pass http://html;}}
}
3、基于浏览器(应用于区分手机和PC或者适配浏览器场景)
http {upstream elinks {server 192.168.204.3;}upstream chrome {server 192.168.204.4;}upstream any {server 192.168.204.4:81;}server {listen      80;server_name  www.web1.com;charset utf-8;location / {proxy_pass http://any;if ($http_user_agent ~* 'elinks') {proxy_pass http://elinks;}if ($http_user_agent ~* 'chrome') {proxy_pass http://chrome;}}}
}
4、基于IP分发
http {upstream bj.server {server 192.168.204.3;}upstream sh.server {server 192.168.204.4;}upstream default.server {server 192.168.204.4:81;}#geo是nginx自带的IP库模块,用来存放ip的geo $geo {# 后缀default、bj、sh字段要和上面upstream集群名保持一致# 当接收到ip请求后,匹配ip库,返回后缀名给geo变量,因此$geo的值          # 为[bj/sh]default default;192.168.204.3/32 bj;192.168.204.4/32 sh;}server {listen      80;server_name  www.web1.com;charset utf-8;location / {proxy_pass http://$geo.server$request_uri;}}
}
4、fair(第三方)
  • 按后端服务器的响应时间来分配请求,响应时间短的优先分配。
5、url_hash(第三方)
  • 按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。

3.4、构建高可用Nginx集群

  • 一个监控+自愈的软件
1、Keepalived监控
  • keepalived的作用是检测服务器的状态,如果有一台web服务器宕机,或工作出现故障,Keepalived将检测到,并将有故障的服务器从系统中剔除,同时使用其他服务器代替该服务器的工作,当服务器工作正常后Keepalived自动将服务器加入到服务器急群众,这些工作全部自动完成,不需要人工干涉,需要人工做的只是修复故障的服务器。
  • Keepalived官网下载地址
    • http://www.keepalived.org/download.html
    • wget http://www.keepalived.org/software/keeepalived-2.0.8.tar.gz
  • Keepalived安装
    • 监控谁就和谁部署在一起,Nginx自己就会检测后端业务服务器状态,所以Keepalived一般用于检测分发器的
#cat keepalived_install.sh#!/bin/bashpkg=keepalived-2.0.8.tar.gztar xf $pkgyum -y install kernel-develIn -s /usr/src/kernels/3.10.0-862.14.4.el7.x86_64/ /usr/src/linuxcd keepalived-2.0.8/yum install openssl-* -y/configure --prefix=/usr/local/keepalivedmakemake installmkdir -pv /etc/keepalivedcp/usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/In-s /usr/local/keepalived/sbin/keepalived /sbin/
2、keepalived的配置文件组成
  • 全局配置(GLOBAL CONFIGURATION)
  • VRRP配置(VRRP CONFIGURATION)
  • LVS配置(LVS CONFIGURATION)
3、配置文件详情
  • global_defs区域
global_defs {notification_email {    # 故障发生时,给谁发送邮件消息acassen@firewall.locfailover@firewall.locsysadmin@firewall.loc}notification_email_from Alexandre.Cassen@firewall.loc    # 通知邮件从哪个地址发出smtp_server 192.168.200.1    # 通知邮件的smtp地址smtp_connect_timeout 30    # 连接smtp服务器的超时时间router_id LVS_DEVEL    # 标识本节点的字符串,故障发生时,邮件通知会用到vrrp_skip_check_adv_addr    # 检查收到vrrp通告中的所有地址会比较耗时,设置此属性,当通告与接收的上一个通告来自同一个master路由器,则跳过检查,默认不跳过检查vrrp_strict    # 严格遵守vrrp协议vrrp_garp_interval 0.1    # 一个接口发送的两个arp之间的延迟vrrp_gna_interval 0.1script_user root    # 设置运行脚本默认用户和组,如果不指定,则默认为keepalived_script(需要该用户存在)
}
  • static_ipaddress、static_routes区域

    • 注:这两个区域配置的是本节点的ip和路由,一般情况下,机器都会存在ip地址和路由信息,因此这两个区域的配置可直接忽略
static_ipaddress {x.x.x.x
}
static_routes {x.x.x.x
}
  • vrrp_script区域
vrrp_instance VI_1 {state MASTER    # 指定keepalived节点的初始状态,MASTER/BACKUPinterface ens33    # vrrp实例绑定的接口,用于发送vrrp包virtual_router_id 51    # 指定vrrp实例idpriority 100    # 指定优先级,优先级高的伪MASTERadvert_int 1    # 发送vrrp包的间隔,即多久进行一次master选举nopreempt    # 指定非抢占模式,默认为抢占模式preempt_delay 300    # master启动多久之后接管资源,前提是抢占模式下authentication {    # 认证区域,认证方式有PASS和HA,推荐使用PASS(密码只识别前8位)auth_type PASS    # 认证方式auth_pass 1111    # 认证密码}virtual_ipaddress {    # 设置虚拟ip192.168.132.16}track_script {    # 设置执行脚本函数nginx_check}garp_master_delay 15    # 当切换为master后多久更新ARP缓存,默认为5秒track_interface {    # 监控以下网卡,如果任意一个不通,则会切换为FAIL状态ens0ens33}
}
  • vrrp_sync_group区域
vrrp_sync_group VG_1 {group {    # 设置vrrp_instance组VI_1VI_2}notify_master /usr/local/keepalived/sbin/to_master.sh    # 切换为master时执行的脚本notify_backup /usr/local/keepalived/sbin/to_backup.sh    # 切换为backup时执行的脚本notify_fault /usr/local/keepalived/sbin/fault.sh    # 出错时执行的脚本notify /usr/local/keepalived/sbin/notify.sh    # 任何状态切换时都会执行该脚本,且在以上三个脚本执行完成之后执行smtp_alert    # 是否开启邮件通知
}
  • vrrp_server区域
virtual_server 192.168.200.100 443 {delay_loop 6    # 延迟轮询时间(单位秒)lb_algo rr|wrr|lc|wlc|lblc|sh|dh    # 后端调试算法lb_kind NAT|DR|TUN    # LVS调度类型persistence_timeout 50    # 会话保持时间persistence_granularity    # lvs会话保持粒度protocol TCP    # 使用的协议sorry_server    # 指定备用机,所有的realserver失败后启用real_server 192.168.201.100 443 {    # 真正提供服务的服务器weight 1    #默认为1,0为失败inhibit_on_failure    # 在服务器健康检查失效时,将其设为0,而不是直接从ipvs中删除notify_up /usr/local/keepalived/sbin/notify_up.sh    # 当服务器健康检查成功时执行的脚本notify_down /usr/local/keepalived/sbin/notify_down.sh    # 当服务器健康检查失败时执行的脚本SSL_GET|HTTP_GET {url {    # 检查url,可指定多个path /    # 请求realserver上的路径digest ff20ad2481f97b1754ef3e12ecd3a9cc    # 使用genhash计算出的摘要信息status_code    # 检查的http状态码}connect_port 80    # 健康检查,如果端口通,则认为服务器正常connect_timeout 3    # 超时时长retry 3    # 重试次数delay_before_retry 3    # 下次重试的时间延迟}TCP_CHECK {connect_timeout 3    # 超时时间retry 3    # 重试次数connect_port 80    # 健康检查端口delay_before_retry 3    # 下次重试的时间延迟 }SMTP_CHECK {host {connect_ip    # 连接ipconnect_port    #连接端口}connect_timeout 3    # 超时时间retry 3    # 重试次数delay_before_retry 3    # 下次重试的时间延迟}MISC_CHECK {misc_path    # 外部脚本路径misc_timeout    # 脚本执行超时时间misc_dynamic    # 如果设置该项,则退出状态码会用来动态调整服务器的权重,返回0,则正常不修改,返回1,则权重改为0}}
}
  • 注:当环境复杂时,会导致keepalived配置文件中内容繁多,不易进行管理,可以将不同集群的配置放在独立的子配置文件中,利用include指令在主配置文件中引入子配置文件

  • 案例展示

! Configuration File for keepalivedglobal_defs {route_id NGINX_DEVEL
}vrrp_script check_nginx {script "/etc/keepalived/nginx_pid.sh"
interval 2
fail 1
}vrrp_instance nginx {state MASTERinterface ens33mcast_src_ip 192.168.137.10virtual_router_id 51priority 100advert_int 1authentication {auth_type PASSauth_pass 1111}track_script {check_nginx}virtual_ipaddress {192.168.137.213/24}
}
# script "/etc/keepalived/nginx_pid.sh"#!/bin/bash
function nginx_kp_check {nginx_pid=`ps -C nginx --no-header |wc -l`
if [ $nginx_pid -eq 0 ] ; then/opt/program/nginx/sbin/nginxsleep 1nginx_pid=`ps -C nginx --no-header |wc -l`if [ $nginx_pid -eq 0 ];thensystemctl stop keepalivedfi
fi
}nginx_kp_check

Nginx-web服务器和反向代理总结相关推荐

  1. 20步打造最安全的Nginx Web服务器

    Nginx是一个轻量级的,高性能的Web服务器以及反向代理和邮箱(IMAP/POP3)代理服务器.它运行在UNIX,GNU/Linux,BSD各种版本,Mac OS X,Solaris和Windows ...

  2. 彻底吃透Web服务器、容器、应用程序服务器与反向代理

    出处:cnblogs.com/vipyoumay/p/7455431.html 我们知道,不同肤色的人外貌差别很大,而双胞胎的辨识很难.有意思的是 Web 服务器/Web 容器/Web 应用程序服务器 ...

  3. 06蚂蚁-高性能Nginx服务器——1.反向代理

    环境准备 CentOS7 7.0 64位 以上+一台外网服务器+一个域名+CDN内容分发 电脑配置 16g以上内存 CentOS7 关闭防火墙 //临时关闭 systemctl stop firewa ...

  4. 【转】Nginx服务器的反向代理proxy_pass配置方法讲解

    [转]Nginx服务器的反向代理proxy_pass配置方法讲解 转自:http://www.jb51.net/article/78746.htm 就普通的反向代理来讲 Nginx的配置还是比较简单的 ...

  5. 20个Nginx Web服务器最佳安全实践

    0个Nginx Web服务器最佳安全实践 20个Nginx Web服务器最佳安全实践  Nginx 是一个轻量级,高性能的Web服务器/反向代理和电子邮件代理(IMAP/POP3),它可以运行在UNI ...

  6. 【Node】node.js实现服务器的反向代理,解决跨域问题

    跨域对于前端来说是一个老大难的问题,许多方法如jsonp.document.domain + iframe...都有或多或少的问题,一个最佳实践就是通过服务器nginx做反向代理,但奈何不懂相关知识, ...

  7. 如何在 FreeBSD 10.2 上安装 Nginx 作为 Apache 的反向代理

    如何在 FreeBSD 10.2 上安装 Nginx 作为 Apache 的反向代理 Nginx 是一款自由开源的 HTTP 和反向代理服务器,也可以用作 POP3/IMAP 的邮件代理服务器.Ngi ...

  8. Nginx的基本介绍反向代理

    什么是nginx Nginx 是异步框架的网页服务器,也可以用作反向代理.负载平衡器和 HTTP 缓存.大部分 Web 服务器使用 Nginx,通常作为负载均衡器. 部署web项目的容器(部署你们写的 ...

  9. nginx 1.16 配置反向代理,http,https,ssl

    需求 之前云服务上仅部署了门户网站,后来要做小程序开发,还有各项目网站.之前是通过域名+端口访问, 现改为启用二级域名,共用公网IP,80(http).443(https)端口,通过nginx按域名做 ...

  10. Linux深入篇之一:配置Nginx Web服务器及多域名主机

    Linux深入篇之一:配置Nginx Web服务器及多域名主机 一.Nginx简介 nginx [engine x]是Igor Sysoev编写的一个HTTP和反向代理服务器,另外它也可以作为邮件代理 ...

最新文章

  1. 20强名单公布!2021 OceanBase 数据库大赛决赛酣战在即!
  2. 基于GNN,强于GNN:胶囊图神经网络的PyTorch实现 | ICLR 2019
  3. 无法启动MySQL数据库
  4. JavaScript函数大全
  5. 新浪微博,请砍掉90%的功能
  6. 计算机与应用化学怎么投稿,计算机与应用化学杂志
  7. 关于sublime-text-2的Package Control组件安装方法,自动和手动
  8. Simulink之变压器隔离的直流-直流变换器
  9. Ubuntu:查询计算机软硬件信息
  10. Andriod开发前准备
  11. [转载] 用pandas或numpy处理数据中的空值(np.isnan()/pd.isnull())
  12. onmouseover|onmouseout和onmouseenter|onmouseleave的区别
  13. Spring源码解析目录
  14. 【数字信号处理】基于Matlab GUI数字均衡器设计【含Matlab源码 904期】
  15. 比较好的java网站[推荐]
  16. 不同iPhone屏幕尺寸
  17. FileZilla连接ubuntu主机时选择21端口无法连接
  18. 10个最佳WordPress Star Rating插件
  19. 智能手机功能设计实现
  20. 《青春有你》新增公益任务 张艺兴蔡依林等当导师

热门文章

  1. 机器视觉-相机镜头光源介绍及选型-7.镜头参数
  2. 微信小程序自定义头部返回按钮及回到首页样式
  3. [旅游]泰国普吉+曼谷8日游
  4. php 线程周期,进程线程,CPU核心数,时间片轮转机制解读
  5. 东北大学山东大学计算机考研,山东大学跟东北大学哪一个更好呢……
  6. 个人网站如何进行备案
  7. 从零单排冲kubebuilder(二)
  8. 微软发布带外更新,紧急修复补丁引发的Kerberos 问题
  9. 计算机网络里面的arp是什么,Arp命令
  10. Linux- 系统随你玩之--玩出花活的命令浏览器-双生姐妹花