Nginx基础

51 阅读5分钟

Nginx

基本使用

目录结构

Nginx的主目录

client_body_temp conf fastcgi_temp html logs proxy_temp sbin scgi_temp uwsgi_temp

sbin: nginx的主程序

基本运行原理

img

上图可知,nginx多进程同时完成用户请求,主进程master用来协调worker进程

配置文件的校验由master进程完成,worker进程读取配置文件,并去寻找文件。

Nginx配置文件

先不看注释部分

worker_processes  1; # 默认为1,表示开启一个业务进程 # 事件驱动模块
events {
    worker_connections  1024; # 单个业务进程可接受连接数 
}
​
​
http {
    include       mime.types; # 引入http mime类型 
    default_type  application/octet-stream; # 如果mime类型没匹配上,默认使用二进制流的方式传输。 
​
    sendfile        on; # 使用linux的 sendfile(socket, file, len) 高效网络传输,也就是数据0拷贝。
​
    keepalive_timeout  65; # keepalive_timeout 65;  ,保持连接,超时时间。
​
    # 虚拟主机 vhost
    server {
        listen       80; # 监听端口号
        server_name  localhost; #域名、主机名
​
        location / { # 匹配路径uri
            root   html;  # 文件根目录
            index  index.html index.htm;     #访问80端口,找到nginx目录下的html目录下的index.html
        }
        error_page   500 502 503 504  /50x.html; # 报错编码对应页面
        location = /50x.html {
            root   html;
        }
​
    }
}
​

未开启sendfile

img

开启后

img

先将数据写入到内核态的缓存中,然后直接写入到socket缓存,socket缓存再发送到网卡,网卡再执行转发

虚拟主机原理

img

TPC/IP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP是应用层协议,主要解决如何包装数据

tcp/ip只能传递一些二进制的数据,以数据流的形式发送给目标服务器,http协议规定双方达到什么程度传输结束。

注意区分域名、dns、IP、地址的关系

域名解析与泛域名解析实战

  • 使用host文件解析域名(利用host文件假装解析域名)

还可以通过域名解析 然后连接到内网

我们在阿里云的dns域名解析上面添加添加了我们域名和内网ip的对应关系,仅仅只是对应关系,所以我们ping域名可以解析成我们的内网ip,由于终端与对应机器在同一局域网所以能通,你换个不在同一内网的不行

域名解析相关企业项目实战技术架构

虚拟主机域名配置
server {
        listen       80; 
        server_name  admin.hong.com; 
​
        location / { 
            root   /www/admin; 
            index  index.html index.htm;     
        }
        error_page   500 502 503 504  /50x.html; 
        location = /50x.html {
            root   html;
        }
    }
 server {
        listen       80; 
        server_name  blog.hong.com blog2.hong.com;  # 注意匹配规则
​
        location / { 
            root   /www/blog; 
            index  index.html index.htm;     
        }
        error_page   500 502 503 504  /50x.html; 
        location = /50x.html {
            root   html;
        }
    }
# 开启端口
firewall-cmd --zone=public --add-port=88/tcp --permanent
firewall-cmd --reload

重加载:systemctl reload nginx

重启:systemctl restart nginx

域名解析规则
  • servername匹配规则

我们需要注意的是servername匹配分先后顺序,写在前面的匹配上就不会继续往下匹配了。

  • 完整匹配

我们可以在同一servername中匹配多个域名

  • 通配符匹配
server_name *.mmban.com
  • 通配符结束匹配
server_name vod.*;
  • 正则匹配
server_name ~^[0-9]+.mmban.com$;
多用户二级域名

img

短网址

image-20220929141708740.png

httpdns

反向代理、反向代理

反向代理

描述:反向代理是指以代理服务器来接受连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器,而且整个过程对于客户端而言是透明的。

隧道式代理:一进一出一个口

反向代理

描述:正向代理意思是一个位于客户端和原始服务器(origin server)之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器),然后由代理向原始服务器转交请求并将获得的内容返回给客户端。

简单的说类似于采用VPN来访问google:

正向代理vs反向代理.png

区别正向代理、反向

都是站在客户端的角度,看代理服务器是帮客户端代理,还是帮服务端代理

正向代理相当于你家的仆人帮你去外面拿东西,反向代理相当于快递公司的快递员给你送快递

需要代理服务器(路由器中转),遇到瓶颈只能提高代理服务器带宽。所以引入Ivs,返回的时候可以不经过代理服务器。

lvs(DR模型)

lvs嵌套在CentOS

img

反向代理在系统架构中的应用场景

img

img

  • URLRewrite hello?a=100 -->hello/100

负载均衡

描述:负载均衡也是Nginx常用的一个功能。简单而言就是当有2台或以上服务器时,根据规则随机的将请求分发到指定的服务器上处理,负载均衡配置一般都需要同时配置反向代理,通过反向代理跳转到负载均衡。

Nginx目前支持自带3种负载均衡策略还有2种常用的第三方策略。

img

使用proyx_pass进行代理配置

浏览器访问localhost就会跳转到http://www.hong.com ,同时域名没有变化(不支持https

可以有多个server。然后根据策略、调度。

server {
        listen       80; 
        server_name  admin.hong.com; 
​
        location / { 
            proxy_pass http://www.hong.com;
            # root   /www/admin; 
            # index  index.html index.htm;   
        }
    }

负载均衡基本配置(轮询案例)

upstream hong {
    server 192.168.102.80 weight = 8 down;
    server 192.168.103.80 weight = 2;
    server 192.168.103.80 weight = 1 backup;
}
​
server {
        listen       80; 
        server_name  admin.hong.com; 
​
        location / { 
            proxy_pass http://hong;
            # root   /www/admin; 
            # index  index.html index.htm;   
        }
    }

负载均衡策略

  • weight:权重
  • down : 当前server暂不参与负载均衡
  • backup : 预留的备份服务器; 其它所有的非backup机器down或者忙的时候,请求backup机器。
  • max_fails : 请求失败次数限制
  • fail_timeout : 经过max_fails后服务暂停时间
  • max_conns : 限制最大的连接数

负载均衡调度算法

  • 轮询:默认算法按时间顺序逐一分配到不同的后端服务器;
  • 加权轮询:Weight值越大,分配到访问几率越高;
  • ip_hash:为每一个请求访问的IPhash结果分配,可以将来自一个IP的固定访问一个后端服务器;

ip_hash 会话粘连, 上面的2种方式都有一个问题,那就是下一个请求来的时候请求可能分发到另外一个服务器,当我们的程序不是无状态的时候(采用了session保存数据),这时候就有一个很大的很问题了,比如把登录信息保存到了session中,那么跳转到另外一台服务器的时候就需要重新登录了,所以很多时候我们需要一个客户只访问一个服务器,那么就需要用iphash了,iphash的每个请求按访问iphash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。

  • url_hash:需要安装模块安装访问的URLhash结果来分配,这样每个URL定向到同一个后端服务器

定向流量转发:

http://hong/registerhttp://hong/login如果hash不一样,sessioncookie会话不能保证。适合固定资源不在统一服务器情况。

  • fair:fair(第三方)按后端服务器 的响应时间来分配请求,响应时间短的优先分配。
  • least_conn:按照某台机器最少连接数的进行分配访问;
  • hash关键数值: hash 自定义 KEY

上面均不多用,做不到动态上下线服务器,一般lua脚本、jwt非对称加密。

动静分离

image.png

静指的是图片、css、js等一些以实际文件形式存在的。动指的是服务器的处理请求。

我们就可以根据静态资源的特点将其做缓存操作,这就是网站静态化处理的核心思路。

upstream test{
  server hong.com:8080;
  server hong.com:8081;
}
​
server {
  listen       80;
  server_name  admin.hong.com;
  
  # 优先级较低
  location / {
        # 没有
        proxy_pass http://192.168.44.104:8080;
  }
​
  # 所有静态请求都由nginx处理,存放目录为nginx中的html
  location ~ .(gif|jpg|jpeg|png|bmp|swf|css|js)$ {
      root  http;
      index index.html index.html;
  }
  # 例子,比如
  #location /css{
    #root html;
    #index index.html index.htm;
  #}
  
​
  # 所有动态请求都转发给tomcat处理
  location ~ .(jsp|do)$ {
      proxy_pass  http://test;
  }
  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
      root   e:wwwroot;
  }
} 

location匹配顺序

  • 多个正则location直接按书写顺序匹配,成功后就不会继续往后面匹配
  • 普通(非正则)location会一直往下,直到找到匹配度最高的(最大前缀匹配)
  • 当普通location与正则location同时存在,如果正则匹配成功,则不会再执行普通匹配
  • 所有类型location存在时,“=”匹配 > “^~”匹配 > 正则匹配 > 普通(最大前缀匹配)

扩展 tomcat基于keepaliveepoll等特性,性能并不比nginx低太多

tomcatvsnginx.png

URLRewrite

rewrite语法格式及参数语法

实现 /2.html -> /index.jsp?pageNum = 2

location / {
        rewrite ^/2.html$    /index.jsp?pageNum=2   redirect;
        proxy_pass http://192.168.44.104:8080;
  }

负载均衡+URLRewrite

img此时nginx:网关服务器,这里面是101通过负载均衡代理配置,rewrite 404:8080(tomcat)

通过防火墙隔绝应用服务器。

  • 打开防火墙
systemctl start firewalld
  • 指定端口和ip访问
firewall-cmd --permanent --add-rich-rule="rule family="ipv4" source address="192.168.44.101" port protocol="tcp" port="8080" accept"
  • 查看已配置规则
firewall-cmd --list-all

完成以上步骤后,发现无法访问192.168.44.104:8080端口,但是可以通过101(这里的localhost)访问104:8080URLrewrite把动态资源的地址隐藏起来了。

upstream test{
  server 192.168.44.102;
  server 192.168.44.104:8080;
}
​
server {
  listen       80;
  server_name  localhost;
  
  location / {
        rewrite ^/[0-9]+).html$    /index.jsp?pageNum=2   break;        
        proxy_pass http://httpds;
  }
​
  location ~*/(js|img|css) {
      root  html;
      index index.html index.html;
  }

防盗链

本质上在我们自己服务器上的资源只能由我们自己服务器能访问。,

http协议中的 referrer

盗链通过referer判断。

防盗链基本配置

vaild_referers none | blocked | server_names | string ....;

  • none,检测Referer头域不存在的情况
  • blocked,检测Referer头域的值被防火墙或者代理服务器删除或伪装的情况。这种情况该头域的值不以"http://"或"https://"开头
  • server_names,设置一个或多个URL,检测Referer头域的值是否是这些URL中的某一个。

在需要防盗链的location中配置

 location ~*/(js|img|css) {
      vaild_referers (none) 192.168.44.101;
      if ($invalid_referer) {
        return 403;
      }
      root  html;
      index index.html index.html;
  }
使用浏览器或curl检测

使用curl测试

curl -I http://192.168.44.101/img/logo.png

带引用

curl -e "http://baidu.com" -I http://192.168.44.101/img/logo.png
基本使用——盗链资源返回页面或提示图片

返回错误码

返回错误页面

整合rewrite返回报错图片

server {
  listen       80;
  server_name  localhost;
  
  location / {
        rewrite ^/[0-9]+).html$    /index.jsp?pageNum=2   break;        
        proxy_pass http://httpds;
  }
​
   location ~*/(js|img|css) {
      vaild_referers none 192.16 8.44.101;
      if ($invalid_referer) {
        rewrite ^/      /img/x.png break;
        # return 401;
      }
      root  html;
      index index.html index.html;
  }
  
  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
        root html;
  }
  
  error_page 401 /401.html;
  location = /401.html {
        root html;
  }

高可用介绍

image.png

为什么要使用nginx的高可用:nginx作为反向代理服务器时,有可能出现宕机的情况,而由于其反向代理的特性,就会导致其他服务器(tomcat等)无法被访问,这样项目就停止工作了。

什么是高可用:nginx的高可用简单来说就是配置了两台(或更多)的nginx服务器,当主服务器宕机时,就会自动切换到备用1+服务器,从而保证项目的持续运行。

高可用的原理: nginx的实现需要借助其他工具(keepalived)来实现。在keepalived中配置一个虚拟IPVIP),同时keepalived会定时检查主服务器的工作状态(通过脚本实现)。在主服务器正常工作时,VIP就会映射到主服务器的IP,此时,虚拟ip对应的物理地址和主服务器IP对应的物理地址是相同的,所以访问虚拟IP即访问主服务器。当主服务器失效时,脚本就会监测到,从而根据预先的配置,找到优先级最高的备用服务器,并将虚拟IP映射到该备用服务器的ip,此时,这两个ip对应的物理地址时相同的。再主服务器回复正常时,又会被检测到,又会自动切换到主服务器。这样就实现了nginx的高可用。

Keepalived

keepalived 配置文件

keepalived只有一个配置文件keepalived.conf,里面主要包括以下几个配置区域,分别是global_defsstatic_ipaddressvrrp_scriptvrrp_instancevirtual_server.