Nginx学习

297 阅读10分钟

环境配置

  1. linux系统检查

    1. ping www.baidu.com. //检查网络
    2. yum list|grep gcc  //列出gcc的部分
    3. intables关闭  
       iptables -L  查看是否开启
       iptables -S  关闭
    4. getenforce 关闭
    
  2. 安装依赖

    1. yum -y install gcc gcc-c++ autoconf pcre-devel make automake
    2. yum -y install wget httpd-tools vim  (httpd-tools加密的)   
    
  3. 创建工作目录

    1. cd /opt/
    2. mkdir app backup download logs work
    // 1. backup 放备用文件 2. app 当代码
    
  4. nginx安装

    Mainline version(开发版本)。Stable version(稳定版本) Legacy version(过去版本)

    • nginx.org/en/download… 下载地址

    • Linux centos

      • 配置rpm源信息

        1. cd /etc/yum.repos.d
        2. vim nginx.repo
        3. 
        [nginx]
        name=nginx repo
        baseurl=http://nginx.org/packages/centos/7/$basearch/
        gpgcheck=0
        enabled=1
        4. 复制上面的代码,保存并退出
        
      • 查看源信息

        yum list|grep nginx
        
      • 安装

        yum install nginx
        
    • 查看文件的存放目录和安装路径

      rpm -ql nginx
      
  5. 工具

    // 查看后台进程
    1. ps -aux|grep nginx
    // 查看本机因为Nginx进程所启用的端口
    2. netstat -luntp|grep nginx
    
  6. cgi配置(common gateway interface 通用网关接口)

    • Web Server 通过cgi协议可以把动态的请求传递给php, jsp, python等应用程序
    • FastCGI实际上是增加了一些扩展功能的CGI,是CGI的改进,描述了客服端和web服务器程序之间传输数据的一种标准
      CGI流程图

nginx的中间件架构

1. 安装目录讲解(rpm -ql nginx)

  1. 配置文件

    • /etc/logrotate.d/nginx
    • 作用:Nginx日志轮转,用于logrotate服务的日志切割
  2. 目录和配置文件

    • /etc/nginx /etc/nginx/nginx.conf
      /etc/nginx/conf.d /etc/nginx/conf.d/default.conf (核心配置)

    • 作用: Nginx主配置文件 先走Nginx的配置文件,如果我们没有配置,就走default.conf默认配置文件

    • 保存和检查配置

      1. nginx -t -c /etc/nginx/nginx.conf  
      // -t 表示配置文件的语法检测  -c 配置文件测试是否成功
      2. nginx -s reload -c /etc/nginx/nginx.conf
      // 重启 并制定配置
      3. ps -aux|grep nginx
      
  3. http协议的关系

    • /etc/nginx/mime.types
    • 作用:设置http协议的Content-Type与扩展名对应关系(不能识别的额外添加)
  4. 执行命令

    • /usr/sbin/nginx(主要这个) /usr/sbin/nginx-debug
    • 作用:Nginx服务的启动管理的终端命令(用于调试和分析)
  5. 缓存

    • /var/cache/nginx
    • 作用: 用于启动服务后的缓存
  6. 日志

    • /var/log/nginx
    • 作用: 存放Nginx的日志

2. 安装编译参数(nginx -V)

编译选项 作用
--prefix=/etc/nginx
--sbin-path=/usr/sbin/nginx
--modules-path=/usr/lib64/nginx/modules
--conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--pid-path=/var/run/nginx.pid
--lock-path=/var/run/nginx.lock
1.安装的目录和路径
2. 可执行文件
3. 安装模块
4. 配置文件路径
5. 错误日志
6. 访问日志
7. 进程ID
8. 加上对象
--http-client-body-temp-path=/var/cache/nginx/client_temp
--http-proxy-temp-path=/var/cache/nginx/proxy_temp
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
--http-scgi-temp-path=/var/cache/nginx/scgi_temp
1. 客户端请求体临时文件
2. 代理临时路径
--user=nginx
--group=nginx
1.Nginx进程启动的用户
2. 指定用户组

3. Nginx的主要配置(重点)

  • /etc/nginx/nginx.conf # 主配置文件
  • /etc/nginx/conf.d/*.conf #包含conf.d目录下面所有的配置文件
  • /etc/nginx/conf.d/default.conf #默认配置
1. cd /etc/nginx
2. vi nginx.conf

3.1 nginx.conf中的http部分

# 语法 
# 使用#可以添加注释,使用$符号可以使用变量
# 配置文件由指令和指令块组成,指令快以{}将多余指令组织在一起
# include 语句允许把多个配置文件组合起来以提升可维护性
# 每行指令以;结尾,指令和参数之间以空格分隔

user nginx; # 设置运行此nginx用户名
worker_processes auto;  # 工作进程数
error_log /var/log/nginx/error.log; # 指定错误日志的路径
pid /run/nginx.pid; # 这是一个文件,里面放的是Nginx的进程号

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024; # 工作进程的最大连接数
}

http {
	   # 定义一个日志格式main
    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;# 指定访问日志的存放位置,格式为main

    sendfile            on; # 零拷贝模式,不走用户空间
    tcp_nopush          on; # 不要主动推,有一定缓存
    tcp_nodelay         on;
    keepalive_timeout   65; # 活动链接的超时时间
    types_hash_max_size 2048;
    # gzip  on; # 是否启动压缩
    include             /etc/nginx/mime.types; # 包含内容和文件名后缀的对应关系
    default_type        application/octet-stream; #默认的Content-type

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf; # 包含其他配置文件

    server { # 每个server对应一个网站
        listen       80 default_server;  # 监听的端口号
        listen       [::]:80 default_server;  
        server_name  _;  # 域名或者ip
        #charset  utf-8;  # 指定字符集
        #access_log  /var/log/nginx/host.access.log main; #指定访问日志的位置和格式
        # root         /usr/share/nginx/html;
        
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
        # 有些指令可以支持正则表达式
        location / { # 匹配所有路径
        		root /usr/share/nginx/html;  # 静态文件根目录
        		index index.html index.htm  # 索引文档
        }

        error_page 404 /404.html;  # 错误页面如果返回的状态码404的话会重定向到/404.html
        location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;  # 把服务器端错误状态码重定向到50x.html上
        location = /50x.html { # 当路径是/50x.html的话,根目录是/usr/share/nginx/html
        	root /usr/share/nginx/html; 
        }
    }
}

如果没有配置server,就会走defalut.conf的文件(/etc/nginx/conf.d/default.conf

server {
    // 对于不同的server,可以根据listen(端口),也可以根据server_name区别
    listen       80;
    server_name  localhost;

    #charset koi8-r;    #access_log  /var/log/nginx/host.access.log  main;
  // 如果开启了nginx,路径:/  目录:/usr/share/nginx/html  文件: index.html index.htm
    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
    # 把服务器端错误状态码重定向到50x.html上
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {  # 当路径是/50x.html的话,根目录是/usr/share/nginx/html
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    # 如果访问的文件名是.php结尾的话,会把此请求转发给http://127.0.0.1
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
	#}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    # 如果访问的文件名是.php结尾的话,会把请求转发给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
    # 如果路径是/.ht的话,deny all 禁止所有人访问 
    #location ~ /\.ht {
    #    deny  all;
    #}
}

3.2 centos7启动服务

  • 监视和控制systemd 的主要命令是systemctl

  • 该命令可用于查看系统状态和管理系统及服务

    命令:systemctl command name.service
    启动:service name start   ->  systemctl start name.service
    停止:service name stop   ->  systemctl stop name.service
    重启:service name restart   ->  systemctl restart name.service
    状态:service name status   ->  systemctl start name.service
    
  • 启动和重启加载

    $ systemctl restart nginx.service
    $ systemctl reload nginx.service
    $ nginx -s reload
    
3.3 日志
  1. 日志类型 curl -v http://localhost

  2. 日志类型

    • /var/log/nginx/access.log 访问日志
    • /var/log/nginx/error.log 错误日志
  3. log_format

    类型 用法
    语法 log_format name [escape=default[json] string]
    默认 log_format combined " "
    Context http
  4. 内置变量

    名称 含义
    $remote_addr 客户端地址
    $remote_user 客户端用户名称
    $time_local 访问时间和时区
    $request 请求行
    $status HTTP请求状态
    $body_bytes_sent 发送给客户端文件内容大小
  5. HTTP请求变量

    • 主要要把-转出下划线,比如User-Agent对应于$http_user_agent

      名称 含义 例子
      arg_PARAMETER 请求参数 $arg_name
      http_HEADER 请求头 $http_referer $http_host $http_user_agent
      sent_http_HEADER 响应头 $sttp_http_cookie

4 Nginx的中间键架构

4.1 http请求

// 1. curl 就相当于window下面的浏览器,打开网页,但是由于Linux没有可视化界面,所以看不到
# curl www.baidu.com
// 2. 查看具体的请求体和请求头, 响应体
# curl -v www.baidu.com
// curl -v www.baidu.com > /dev/null 把请求放入一个类似临时文件中,方便查看

4.2 Nginx的日志类型

  1. error.log : 记录nginx处理http请求的错误状态以及nginx本身服务运行的错误状态(比较简单)

    #  1. 进入 /etc/nginx 下面的nginx.conf
    #  2. /var/log/nginx/error.log warn  日志的目录
    #  3. error_log  /var/log/nginx/error.log warn;
    $ tail -f /var/log/nginx/error.log warn  // 循环查看日志的内容
    
  2. access.log :每一次http请求的访问状态,用于分析每一次请求和用户的行为

    // main是格式  log_format和acces_log对应 
    http {
        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;
    }
    # 字段意义 (-)
    $remote_addr  客户端地址
    $remote_user  http客户端请求nginx的log_format日志的用户名(没有开启认证模块是不会记录的)
    $time_local   nginx的时间
    $request  request头的请求行
    $status reponse返回的状态
    $body_bytes_sent  从服务端返回给客户端body信息的大小
    $http_referer   上一级页面的url地址
    $http_user_agent  客户端的类型
    $http_x_forwarded_for  协议标准的头,记录每一级http请求所携带的信息  
    
  3. log_ format(只能配置到大的http范围内)

    作用: 实现日志的分析

    类型:

    Syntax: log_format name [escape=default|json] string ...;
    Default: log_format combined "...";
    Context: http
    

4.3 Nginx 变量

1. HTTP请求变量: arg_PARAMETER、http_HEADER(http头信息)、sent_http_HEADER
2. 内置变量: Nginx内置的
3. 自定义变量: 自己定义

4.4 Nginx 模块讲解

Nginx官方模块

1. nginx -V  (查看安装编译参数, 里面就包裹了Nginx的官方模块)
2. --with后面基本就是官方模块
编译选项 作用
--with-http_stub_status_module Nginx的客户端状态,监控Nginx的状态信息
--with-http_random_index_module 目录中选择一个随机主页
--with-http_sub_module HTTP内容替换
  • 官方模块语法

    1. http_stub_status_module的配置:

      Syntax:   stub_status  
      Default: --(默认没有配置)
      Context: (server/location下才可以)
      
      
    2. http_random_index_module的配置 (随机展示首页,不会展示隐藏文件)

      Syntax: random_index on|off;
      Default: random_index off;
      Context: location
      
    3. http_sub_module的配置

      // 替换指定的字符串
      Syntax: sub_filter string replacement;
      Default: --
      Context: http server location;
      // 缓存
      Syntax: sub_filter_last_modified on|off;
      Default: sub_filter_last_modified off;
      Context: http server location;
      // 默认替换第一个匹配的值
      Syntax: sub_filter_once on|off;
      Default: sub_filter_once on;
      Context: http server location;
      
  • 使用说明:

    1. http_stub_status_module
    1. 由于http_stub_status_module模块只能在server/location中,默认也是没有配置的,所以我们修改nginx的默认配置
    2. cd /etc/nginx/conf.d 
    3. vim default.conf
    4. 添加location 
    location /mytest {
    	stub_status on;
    }
    5.浏览器访问地址  http://www.huangchucaivip.cn/mytest
    	Active connections: 2
    	server accepts handled requests
     	902 902 638(总的请求数) 	
    	Reading: 0 Writing: 1 Waiting: 1 (keep-alive的时候)
    
    1. http_random_index_module
    1. cd /etc/nginx/conf.d 
    2. vim default.conf
    3. 修改location,随机展示/opt/app/code下面的文件
        location / {
            root   /opt/app/code;
            # index  index.html index.htm;
            random_index on;
        }
    
    1. http_sub_module
    location / {
        root   /opt/app/code;
        index  index.html index.htm;
        sub_filter 'hcc' 'HCC'; // 替换hcc 成 HCC
        sub_filter_once off;	// 全部替换		
    }
    

4.5Nginx的请求限制

  1. 连接频率限制 - limit_conn_module

     Syntax:  limit_conn_zone key zone=name:size
     Default: --
     Context: http
     
     Syntax: limit_conn zone number;
     Default: --
     Context: http, server, location
    
  2. 请求频率限制 - limit_req_module

我们知道http协议是基于TCP协议下的传输,一次TCP请求至少可以产生一次HTTP请求,http2.0的多路复用和http1.1的顺序性TCP复用,都是一个TCP请求连接多个HTTP请求。

所以对于请求的限制会大于对于连接的限制,因为一个连接可以发送多个HTTP请求

Syntax:  limit_req_zone key zone=name:size rate=rate
Default: -- 
Context: http

Syntax: limit_req zone=name [burst=number] [nodelay];
Default: --
Context: http, server, location

工具

  1. ab: 基于Apache的一个压力测试工具

    $ ab -n 50 -c 20 http://www.huangchucaivip.cn/1.html
    总共发送50次,同时并发20
  2. 请求限制,每秒可以访问数

    limit_req_zone

    # 可以以IP为key  zone为空间名称  size为申请空间的大小
    Syntax: limit_req_zone key zone=name:size rate=rate;
    Default:  --
    Context: http(定义在server以外)
    

    limit_req

    # zone 名称  number限制的数量
    Syntax: limit_req zone=name [burst=number] [nodelay]; 
    Default:  --
    Context: http,server, location
    
  3. 限制连接数

    limit_conn_zone

    # 可以以IP为key  zone为空间名称  size为申请空间的大小
    Syntax: limit_conn_zone key zone=name:size;
    Default:  --
    Context: http,server, location
    
     #  $binary_remote_addr 是一个变量 远程ip地址
     #  zone=req_zone:1m  表示一个内存区域大小为1m,并且设定了名称为`req_zone`
     #  rate=1r/s  表示请求的速率是1秒一个请求
     #  zone=req_zone; 表示这个参数对应的全局设置就是req_zone的那个内存区域
     limit_req_zone $binary_remote_addr zone=req_zone:1m rate=1r/s;  # 每秒处理一个
     limit_conn_zone $binary_remote_addr zone=conn_zone:1m;
     server {
         listen       80;
         server_name  localhost;
     
         #charset utf-8;
         #access_log  /var/log/nginx/host.access.log  main;
         location / {
             root   /opt/app/code;
             index  index.html index.htm;
             # 服务端同一时刻只允许一个ip访问
             limit_conn conn_zone 1;  
             // 三个限速返回,其他直接返回503,相比于limit_req zone=req_zone会少3个错误日志
             #limit_req zone=req.zone burst=3 nodelay;  
             // 三个限速返回
             #limit_req zone=req.zone burst=3;
            
             limit_req zone=req_zone;
         }
         ...
     }
    
4.6 Nginx的访问控制
  1. 基于IP的访问控制 - http_access_module

    // 允许
    Syntax: allow address | CIDR | unix: |all;
    Default: --
    Context: http, server, location, limit_except
    
    // 拒绝
    Syntax: deny address | CIDR | unix: |all;
    Default: --
    Context: http, server, location, limit_except
    
    // 使用 ~ 表示后面跟着的是一个正则表达式
    location ~ ^/admin.html {
    	root  /opt/app/code;
    	index index.html index.htm;
    	allow 10.100.146.33;
      deny all;
    } 
    

    局限性: http_access_module中间键只会记录最后访问的ip地址,如果我们使用转发的话,就不能限制住原始的ip地址了。

  2. 基于用户的信任登录 - http_auth_basic_module

    // 账号和密码
    Syntax: auth_basic string | off;
    Default: auth_basic off; (默认关闭)
    Context: http, server, location, limit_except
    
    // 文件(存放账号和密码,密码需要加密: htpasswd)
    Syntax:	auth_basic_user_file file;
    Default:	—
    Context:	http, server, location, limit_except
    // 使用 (www.huangchucaivip.cn/admin.html)
    # 1. 安装密码加密的软件htpasswd
    # 2. htpasswd -c ./auth_conf hcc
    # 3. 修改文件
    location ~ ^/admin.html {	
    	root  /opt/app/code;	
    	auth_basic "Auth access test! input you password!";	
    	auth_basic_user_file /etc/nginx/auth_conf;  (密码存放目录)	
    	index index.html index.htm;
    }
    
  3. http_x_forwarded_for: 它是一个http的请求的一个字段,会不断的带着请求经过的ip地址。这样我们就可以得到所有的访问ip地址(但是不是所有的请求都统一)

4.7 静态资源WEB服务

  1. 静态资源类型: 非服务器动态运行生成的文件
类型 种类
浏览器端类型 HTML、CSS、JS
图片 JPEG、GIF、PNG
视频 FLV、MPEG
文件 TXT、等任意下载文件
  1. 静态资源服务场景-CDN(就近原则)

    image

  2. 静态资源web服务的核心模块和语法

  • 文件读取,不需要进过用户内核直接发送文件

    Syntax: sendfile on | off;
    Default: sendfile off;
    Context: http, server, location, if in location
    
  • tcp_nopush: 缓存一段时间,把多个包做成一个组合,一次性发送给客户端

    Syntax: tcp_nopush on | off;
    Default: tcp_nopush off;
    Context: http, server, location;
    

    作用: sendfile开启的情况下,提高网络包的传输效率

  • tcp_nodelay: 数据包及时发送给客户端,不要等待

    Syntax: tcp_nodelay on | off;
    Default: tcp_nodelay off;
    Context: http, server, location;
    

    作用:keepalive连接下,提高网络包的传输实时性

    • 压缩: 压缩传输

      // 压缩
      Syntax: gzip on|off
      Default: gzip off;
      Context: http, server, location, if in location
      // 压缩比例
      Syntax: gzip_comp_level level;
      Default: gzip_comp_level 1;
      Context: http server location;
      // 服务版本
      Syntax: gzip_http_version 1.0|1.1
      Default: gzip_http_version 1.1;
      Context: http, server, location;
      
      // gzip_min_length 1k; 小于1k的文件不压缩
      // 对应的模块
      1. http_gzip_static_module  预读gzip功能(优先返回gzip压缩的内容)
      
    • 服务器压缩,浏览器解压,减少中间网络传输的网络消耗。

      # 图片不压缩
      location ~ .*\.(jpg|png|gif) {
      	gzip off;
      	root /usr/share/nginx/html
      }
      location ~ .*\.(html|css|js) {
      	gzip on;
      	gzip_min_length 1k;
      	gzip_http_version 1.1;
      	gzip_comp_level 9;
      	gzip_types text/css application/javascript;
      	root /usr/share/nginx/html
      }
      
      location ~ ^/download {
        gzip_static on;  # 先扫描文件后缀是.gz的文件,然后直接发送给客户端,提前压缩,省去了获取的时候压缩
        tcp_nopush on;
      	root /usr/share/nginx/html
      }
      
    • 服务器缓存 expires

      // 添加Cache-Control、Expires头
      Syntax: expires[modified] time;
      Default: expires off;
      Context: http, server, location, if in location
      
      location ~ .*\.(jpg|png|gif) {
      	expires 24h;
      	root /usr/share/nginx/html
      }
      
    • 跨域访问

      Syntax: add_header name value [always];
      Default: --;
      Context: http, server, location, if in location 
      Access-Control-Allow-Origin
      
      location ~ .*\json$ {
        add_header Access-Control-Allow-Origin http://127.0.0.1:3000
        add_header Access-Control-Allow-Methods GET POST PUT DELETE OPTIONS;
        root /data/json 
      }
      
    • 防盗链($http_referer)

      我们都知道http的请求头中会携带Referer参数,来说明页面的来源

      Syntax: valid_referers none | blocked | server_names | string | IP;
      Default: --;
      Context: server, location
      // 说明
      1. none: “Referer” 来源头部为空的情况
      2. blocked: 不以http或https开头的字段
      3. 具体的ip
      location ~ .*\.(jpg|png|gif) {
        	root /usr/share/nginx/html
        // 使用 验证通过为0,不通过为1
        valid_referers none blocked 119.29.161.100;  
        # 注意没有s  referer 注意要有空格;
      	if ($invalid_referer) {
              return 403;
        }
      }
      
      

4.8 代理服务

Syntax: proxy_pass URL;
Default: --;
Context: location, if in location

# url的格式
1. http://location:8000/uri/ (http协议)
2. https://192.168.1.1:8000/url/ (https协议)
3. http://unix:/tmp/backend.socket:/uri/;

# 主要的使用
location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_redirect default;
    proxy_set_header Host $http_host;   // 额外的添加请求头
    proxy_set_header X-Real-IP $remote_addr;
    proxy_connent_timeout 30;
    proxy_send_timeout 60;
    proxy_read_timeout 60;
    proxy_buffer_size 32k;
    proxy_buffering on;
    proxy_buffers 4 128k;
    proxy_busy_buffers_size 256k;
    proxy_max_temp_file_size 256k;
}
# 以api开头的交给3000端口处理
location ~ ^/api {
   	proxy_pass http://127.0.0.1:3000;
}
  1. 正向代理:

    • 正向代理的对象是客户端,服务器看不到真正的客户端

    • 往往不知道真实的客户端的地址,需要客户端做相应的改动,例如我们翻墙的时候设置的浏览器的插件(switchyOmega)

    • 图解

      image

    • 例子

      # 正向代理
      
      # A不是116.62.103.228服务器 不能直接访问www.huangchucai.cn/test.html
      
      1./opt/app/code  下面有一个jesonc.html  (<h1>Jeson</h1>)
      
      2./ect/nginx/cof.d  下面的admin.conf  
      
        location / {
      
           # 不等于116.62.103.228就返回403
      
           if ( $http_x_forwarded_for !~* "^116\.62\.103\.228") {
      
      	        return 403
      
      	   }
      
           root /opt/app/code;
      
           Index index.html index.htm
      
        }
      
      # B登录228服务器配置正向代理
      1./etc/nginx/con.d/zx.proxy.conf 
      
      server {
      
      	listen  80;
      
      	resolver 8.8.8.8(谷歌的DNS解析)
      
      	location / {
      
      		proxy_pass  http://$http_host$request_uri;
      
      	}
      
      }
      
      # www.huangchucai.cn/test.html 
      
      # $http_host:  主机名   www.huangchucai.cn
      
      # $request_uri: 参数  test.html
      
      # 2.正向代理
      # 浏览器设置代理(switchysharp  116.62.103.228:80)  => 浏览器输入 jeson.t.imooc/jesonc.html =>  代理就会走116.62.103.228:80  => 228服务器然后走jeson.t.imooc/jesonc.html  => jeson.t.imooc可以让228服务器通过 => 返回结果
      
      
  2. 反向代理

    • 反向代理代理的是服务端,客户端看不到真正的服务端

    • 图解

      image

    • 例子

      # 8080端口
      # /opt/app/code2 下面有一个test_proxy.html
      location / {
      		root /opt/app/code2;
      		index index.html index.htm
      }
      # 服务器开启80端口,对外开放  fx.proxy.conf
      location ~ /test_proxy.html$ {
      		proxy_pass http://127.0.0.1:8080
      }
      # 反向代理
      # 客户端请求服务器80端口 => 服务器80端口通过proxy_pass 去请求服务器的8080端口 => 返回给客户端 
      
      
  3. 正向代理和反向代理的区别

    区别在于对象的不一样

    正向代理代理的对象是客户端,往往服务器不知道真正的客户端(例如:翻墙)

    反向代理代理的对象是服务端,客户端以为自己发送给了真实的服务器,但是服务器内部进行了转换,例如Nginx代理服务器

4.9 负载均衡调度器SLB

  1. 利用pass_proxy 和 upstream

    # 1. upstream写在server的外面  
    upstream hcc {
      server 119.29.161.100   weight=5;
      server 119.29.161.100:8080 down;
      server 119.29.161.100:9999 backup;
    }
    server {
      listen 8001;
      server_name  localhost;
      location / {
        #root /Users/huangchucai/Desktop/code;
        index index.html index.htm;
        proxy_pass http://hcc;
      }
    }
    
  2. 配置规则

    down 当前server暂时不参与负载均衡
    backup 预备的备份服务器
    max_fails 允许请求失败的次数
    fail_timeout 经过max_fails失败后,服务暂停的时间
    max_conns 限制最大的接收的连接数
  3. 调度算法, 分配方式

    轮询 按时间顺序逐一分配到不同的后端服务器
    加权轮询 weight值越大,分配到访问几率越高
    ip_hash 每个请求访问按IP的hash结果分配,这样来自同一个IP的固定访问一个后端服务器(有弊端,如果客户端有代理的话,记录的是代理服务器的ip,无法定位到用户真正的ip, 始终定位到的是代理的ip)
    least_conn 最少链接数,那个机器连接数少就分发
    url_hash 按照访问的URL的hash结果来分配请求,是每个URL定向到同一个后端服务器
    hash关键数值 hash自定义的key
    # ip_hash
    upstream hcc {
      ip_hash;
      server 119.29.161.100;
      server 119.29.161.100:8080;
    }
    ## url_hash和hash关键值是一个意思,一般在一起使用
    # url_hash (nginx 1.72)
    Syntax: hash key [consistent];
    Default: --;
    Context: upstream 
    
    upstream hcc {
      hash $request_uri;  // todo 只提取路径  /url?h&&! 
      server 119.29.161.100;
      server 119.29.161.100:8080;
    }
    

4.10 动态缓存

  1. proxy_cache_path

    参数 含义
    /opt/app/cache 存放目录
    levels=1:2 目录的分级(2层目录分级)
    keys_zone imooc_cache:10m 定义开辟的zone空间的名字,大小为10兆( proxy_cache)
    max_size 最大的大小
    inactive 在60分钟内,缓存文件没有被访问就删除
    use_temp_path 临时的存放文件(一般会删除)
  2. 具体配置

upstream hcc {
  ip_hash;
  server 119.29.161.100;
  server 119.29.161.100:8080;
}
## 最先配置
proxy_cache_path  /opt/app/cache levels=1:2 keys_zone=imooc_cache:10m max_size=10g 
inactive=60m use_temp_path=off;
server {
    listen  80;
    server_name localhost jeson.t.imooc.io;
    access_log /var/log/nginx/test_proxy.access.log main;
    location / {
        proxy_cache imooc_cache; // cache 空间  proxy_cache off;关闭缓存
        proxy_pass http://imooc; // 代理的模式
        proxy_cache_valid 200 304 12h; // 对于请求的为200和304的缓存 12小时过期
        proxy_cache_valid any 10m; // 对于除了200,304的缓存10分钟
        proxy_cache_key $host$uri$is_args$args; //重写cache的key
        add_header Nginx-Cache "$upstream_cache_status"; // 增加头信息
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; // 如果upstream中的server的有一台返回的是500的错误代码,就跳过这台服务器,走下一台服务器
        include proxy_params;
    }
}
  1. 让部分页面不缓存
# proxy_no_cache
Syntax:  proxy_no_cache string ...;
Default: --;
Context http, server, location;

server {
    listen  80;
    server_name localhost jeson.t.imooc.io;
    access_log /var/log/nginx/test_proxy.access.log main;
    # 部分的请求不缓存
    if ($request_uri ~ ^/(url3|login|register|password\/reset)) {
    	set $cookie_nocache 1;    
    }
    location / {
        proxy_cache imooc_cache; // cache 空间  proxy_cache off;关闭缓存
        proxy_pass http://imooc; // 代理的模式
        proxy_cache_valid 200 304 12h; // 对于请求的为200和304的缓存 12小时过期
        proxy_cache_valid any 10m; // 对于除了200,304的缓存10分钟
        proxy_cache_key $host$uri$is_args$args; //重写cache的key
        add_header Nginx-Cache "$upstream_cache_status"; // 增加头信息
        proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        include proxy_params;
    }
}
  1. 大文件分片请求
# http_slice_module
Syntax: slice size;
Default: slice 0;
Context: http, server, location;

基于中间件的深度学习

1. 动静分离

  • 作用:分离资源,减少不必要的请求消耗,减少请求延时。
 upstream nodeServer {
   server  127.0.0.1:1234;  // 服务器开启一个1234的服务
 }
 server {
   listen       80;
   server_name  119.29.161.100 hcc.nginx.com;
   sendfile on;
   charset utf-8;
   access_log  /var/log/nginx/host.access.log  main;
   root /opt/app/code; // 资源根目录
   location ~ \.jsp$ { // 假如这是一个动态资源
 	proxy_pass http://nodeServer;
 	index index.html index.htm;
   }
   location ~  \.(jpg|png|gif)$ {  // 静态资源
 	expires 1h;
 	gzip on;
   }
   location / {
 	index index.html index.htm;
   }
 }

2. Rewrite规则

rewrite: 实现url重写以及重定向

  • 场景

    1. URL访问跳转,支持开发设计(页面跳转,兼容性支持,展示效果等)
    2. SEO优化
    3. 维护 (后台维护,流量转发等)
    4. 安全(将真实的网站进行伪装)
  • 配置语法

    Syntax: rewrite regex replacement [flag];
    Default: --;
    Context: server, location, if;
    
    //eg: rewrite ^(.*)$ /pages/maintain.html break
    
  • rewrite规则的优先级

    1. 执行server块的rewrite指令
    2. 执行location匹配
    3. 执行选中的location中的rewrite
  • rewrite的规则书写

  • flag的配置

    类型 含义
    last 停止rewrite检测(会模拟下一个请求,返回对应的数据)
    break 停止rewrite检测 (不会模拟下一个请求)
    redirect 返回302临时重定向,地址栏会显示跳转后的地址,浏览器每次都会请求服务器,返回服务器返回重定向的地址,关掉服务器后,不会有响应。
    permanent 返回301永久重定向,地址栏会显示跳转后的地址,关掉服务器后,浏览器会根据缓存实现重定向

    last和break的区别:

    server {
        listen       80;
        server_name  119.29.161.100 hcc.nginx.com;
        sendfile on;
        charset utf-8;
        error_log /var/log/nginx/host.error.log;
        access_log  /var/log/nginx/host.access.log  main;
        root /opt/app/code;
        location ~ ^/break {
        	rewrite ^/break /test/ break;
        }
        location ~  ^/last {
    		#rewrite ^/last /test/ last;
       		rewrite ^/last /test/ redirect;
        }
        location /test/ {
       		default_type application/json;
    		return 200 '{"status": "success"}';
        }
    }
    
    1. 直接请求www.huangchucaivip.cn/test/ 会返回200 ,{status: "success"}
    2. Break: 当location 以break开头的时候,会被rewrite到 www.huangchucaivip.cn/test/ 去寻找/opt/app/code/test 文件下面的index.html文件,如果没有找到就返回403,不会走下面的其他location
    3. Last: 当匹配到以last开头的时候,就会被rewrite到www.huangchucaivip.cn/test/ , 发现下面有一个location 的路径匹配到了,就会直接的定位到,不会去寻找/opt/app/code/test 文件下面的index.html文件。如果没有下面的一个location /test/ ,就会去寻找/opt/app/code/test 文件下面的index.html文件