• Nginx小总结


    1.基础介绍

    1.1安装

    1.1.1 pcre

    为了支持nginx的重写rewrite module,需要安装pcre library.

    [root@bogon home]# yum install pcre pcre-devel
    Loaded plugins: fastestmirror, refresh-packagekit, security
    Setting up Install Process
    Determining fastest mirrors
     * base: mirrors.neusoft.edu.cn
     * extras: mirrors.neusoft.edu.cn
     * updates: mirrors.aliyun.com
    base                                                                                                        | 3.7 kB     00:00     
    extras                                                                                                      | 3.4 kB     00:00     
    extras/primary_db                                                                                           |  29 kB     00:00     
    http://mirrors.aliyun.com/centos/6.10/updates/x86_64/repodata/repomd.xml: [Errno 14] PYCURL ERROR 6 - "Couldn't resolve host 'mirrors.aliyun.com'"
    Trying other mirror.
    updates                                                                                                     | 3.4 kB     00:00     
    updates/primary_db                                                                                          |  11 MB     00:39     
    Package pcre-7.8-7.el6.x86_64 already installed and latest version
    Resolving Dependencies
    --> Running transaction check
    ---> Package pcre-devel.x86_64 0:7.8-7.el6 will be installed
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ===================================================================================================================================
     Package                          Arch                         Version                            Repository                  Size
    ===================================================================================================================================
    Installing:
     pcre-devel                       x86_64                       7.8-7.el6                          base                       320 k
    
    Transaction Summary
    ===================================================================================================================================
    Install       1 Package(s)
    
    Total download size: 320 k
    Installed size: 957 k
    Is this ok [y/N]: y
    Downloading Packages:
    pcre-devel-7.8-7.el6.x86_64.rpm                                                                                                                                                                                                                        | 320 kB     00:01     
    Running rpm_check_debug
    Running Transaction Test
    Transaction Test Succeeded
    Running Transaction
      Installing : pcre-devel-7.8-7.el6.x86_64                                                                                                                                                                                                                                1/1 
      Verifying  : pcre-devel-7.8-7.el6.x86_64                                                                                                                                                                                                                                1/1 
    
    Installed:
      pcre-devel.x86_64 0:7.8-7.el6                                                                                                                                                                                                               
    Complete!
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    1.1.2 安装zlib

    • zlib
      适用于数据压缩的函式库,由Jean-loup Gailly (负责compression)和 Mark Adler (负责decompression)开发。
      zlib被设计成一个免费的、通用的、法律上不受阻碍(即没有被任何专利覆盖)的无损数据压缩库。zlib几乎适用于任何计算器硬件和操作系统。
      zlib本身的数据格式可以进行跨平台的移植。 与在Unix上适用的LZW压缩方法 以及 GIF 图像压缩不同,zlib中适用的压缩方法从不对数据进行拓展。(LZW在极端情况下会导致文件大小变为原来的两倍、甚至三倍)。zlib的内存占用也是独立于输入数据的,并且在必要的情况下可以适当减少部分内存占用。
    #cd /usr/local/src 
    #wget http://www.zlib.net/zlib-1.2.11.tar.gz 
    #tar -xvzf zlib-1.2.11.tar.gz 
    #cd zlib-1.2.11
    #./configure 
    #make 
    #make install
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1.1.3 安装nginx

    [root@bogon home]# cd /usr/local/src/
    [root@bogon src]# pwd
    /usr/local/src
    [root@bogon src]# wget http://nginx.org/download/nginx-1.16.1.tar.gz
    --2020-10-06 08:55:33--  http://nginx.org/download/nginx-1.16.1.tar.gz
    Resolving nginx.org... 52.58.199.22, 3.125.197.172, 2a05:d014:edb:5704::6, ...
    Connecting to nginx.org|52.58.199.22|:80... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 1032630 (1008K) [application/octet-stream]
    Saving to: “nginx-1.16.1.tar.gz”
    
    100%[====================================================================================================================================================================================================================================>] 1,032,630   4.44K/s   in 3m 7s   
    
    2020-10-06 08:58:43 (5.39 KB/s) - “nginx-1.16.1.tar.gz” saved [1032630/1032630]
    
    [root@bogon src]# 
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    cd /usr/local/src/
    wget http://nginx.org/download/nginx-1.16.1.tar.gz
    tar zxvf nginx-1.16.1.tar.gz 
    cd nginx-1.16.1
    ./configure --prefix=/usr/local/nginx
    make && make install
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1.1.4 安装后目录查看

    [root@bogon nginx]# pwd
    /usr/local/nginx
    [root@bogon nginx]# ll
    total 16
    drwxr-xr-x. 2 root root 4096 Oct  6 09:15 conf 配置文件
    drwxr-xr-x. 2 root root 4096 Oct  6 09:15 html 网页文件
    drwxr-xr-x. 2 root root 4096 Oct  6 09:15 logs 日志文件
    drwxr-xr-x. 2 root root 4096 Oct  6 09:15 sbin 主要二进制程序
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    1.1.5 注意

    1.1.5.1 自动创建目录

    不要自己新建一个/usr/local/nginx目录,因为make&&make install会自动生成一个/usr/local/nginx,导致冲突而无法安装

    1.1.5.2 缺少zlib
    root@bogon nginx-1.16.1]# ./configure --prefix=/usr/local/nginx 后的问题    
    ./configure: error: the HTTP gzip module requires the zlib library.
    You can either disable the module by using --without-http_gzip_module
    option, or install the zlib library into the system, or build the zlib library
    statically from the source with nginx by using --with-zlib= option.
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.2 常用基础命令

    启动命令
     ./sbin/nginx 
     
    指定配置启动
    /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf 
    
    # 帮助
    nginx -h
    #重新加载日志
    nginx -s reload
    #关闭
    nginx -s stop
    # 重读日志(和信号量 USR一样)
    nginx -s reopen
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    1.3 nginx进程

    [root@bogon ~]# ps -ef|grep nginx
    root      3296     1  0 23:39 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
    nobody    3297  3296  0 23:39 ?        00:00:00 nginx: worker process      
    root      3372  3196  0 23:52 pts/0    00:00:00 grep nginx
    
    • 1
    • 2
    • 3
    • 4

    master :主进程
    worker :工作进程

    2.信号量

    2.1 基本语法

    Kill -信号选项 nginx的主进程号
    
    • 1

    注意是 主进程号

    信号选项明细:

    TERM, INT	Quick shutdown
    QUIT	Graceful shutdown  优雅的关闭进程,即等请求结束后再关闭
    HUP	Configuration reload ,Start the new worker processes with a new configuration Gracefully shutdown the old worker processes
    改变配置文件,平滑的重读配置文件
    USR1	Reopen the log files 重读日志,在日志按月/日分割时有用
    USR2	Upgrade Executable on the fly 平滑的升级
    WINCH	Gracefully shutdown the worker processes 优雅关闭旧的进程(配合USR2来进行升级)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    举例:

    ## 关闭主进程
    [root@bogon ~]# ps -ef|grep nginx
    root      3296     1  0 23:39 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
    nobody    3297  3296  0 23:39 ?        00:00:00 nginx: worker process      
    root      3372  3196  0 23:52 pts/0    00:00:00 grep nginx
    [root@bogon ~]# kill -INT 3296
    [root@bogon ~]# ps -ef|grep nginx
    root      3449  3196  0 00:03 pts/0    00:00:00 grep nginx
    [root@bogon ~]# 
    
    
    ## 会发现如果杀worker进程会被主进程产生新的work进程
    [root@bogon ~]# /usr/local/nginx/sbin/nginx
    [root@bogon ~]# ps -ef|grep nginx
    root      3453     1  0 00:04 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
    nobody    3454  3453  0 00:04 ?        00:00:00 nginx: worker process      
    root      3456  3196  0 00:04 pts/0    00:00:00 grep nginx
    [root@bogon ~]# kill -INT 3454
    [root@bogon ~]# ps -ef|grep nginx
    root      3453     1  0 00:04 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
    nobody    3459  3453  0 00:04 ?        00:00:00 nginx: worker process      
    root      3461  3196  0 00:04 pts/0    00:00:00 grep nginx 
    [root@bogon ~]# kill -INT 3459
    [root@bogon ~]# ps -ef|grep nginx
    root      3453     1  0 00:04 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
    nobody    3465  3453  0 00:05 ?        00:00:00 nginx: worker process      
    root      3467  3196  0 00:05 pts/0    00:00:00 grep nginx
    [root@bogon ~]# 
    
    ## 修改配置文件后用,不用重启直接使用HUP直接生效
    [root@bogon ~]# kill -HUP 3454
    
    
    ## 切换日志文件 
    //(先将当前运行的日志mv一个新名称,此时日志还会继续在新名称的文件中产生, 然后执行kil -USR 后 则可以新名称日志不增长,日志产生在旧名称中)
    [root@bogon ~]# kill -USR1 3454
    
    ## 直接操作执行nginx主进程
    Kill -USR1 `cat /xxx/path/log/nginx.pid`
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    3.常用配置

    配置文件路径: /usr/local/nginx/conf/nginx.conf

    3.1 概述

    // 全局区
    worker_processes 1; // 有1个工作的子进程,可以自行修改,但太大无益,因为要争夺CPU,一般设置为 CPU数*核数
    
    Event {
    // 一般是配置nginx连接的特性
    // 如1个word能同时允许多少连接
     worker_connections  1024; // 这是指 一个子进程最大允许连1024个连接
    }
    
    http {  //这是配置http服务器的主要段
         Server1 { // 这是虚拟主机段
           
                Location {  //定位,把特殊的路径或文件再次定位 ,如image目录单独处理
                }             /// 如.php单独处理
    
         }
    
         Server2 {
         }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    3.2 http服务段

    ## 1: 基于域名的虚拟主机
    
        server {
            listen 80;  #监听端口
            server_name abc.com; #监听域名
    
            location / {
                    root /var/www/abc.com;   #根目录定位
                    index index.html;
            }
        }
    
    ## 例子2: 基于端口的虚拟主机配置
        server {
            listen 8080;
            server_name 192.168.1.204;
    
            location / {
                    root /var/www/html8080;
                    index index.html;
            }
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    4.日志配置

    不同的server配置可以使用不同的配置

    4.1 常用日志配置

    ## 格式名称(main)及模板
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    
    ### 配置含义                  
        远程IP- 远程用户/用户时间 请求方法(如GET/POST) 请求体body长度 referer来源信息
        http-user-agent用户代理/蜘蛛 ,被转发的请求的原始IP
        http_x_forwarded_for:在经过代理时,代理把你的本来IP加在此头信息中,传输你的原始IP                  
                      
    
    ## 日志使用名称为main的模板
    access_log  logs/access.log  main;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    4.2 自定义日志配置

    除了main格式,你可以自定义其他格式.

    log_format  mylog '$remote_addr- "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';
    
    access_log logs/access_8080.log mylog;   
    #配置含义 声明log   log位置          log格式;                    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4.3 定时切割日志

    shell+定时任务+nginx信号管理,完成日志按日期存储:
    凌晨00:00:01,把昨天的日志重命名,放在相应的目录下,再USR1信息号控制nginx重新生成新的日志文件

    #!/bin/bash
    base_path='/usr/local/nginx/logs'
    log_path=$(date -d yesterday +"%Y%m")
    day=$(date -d yesterday +"%d")
    mkdir -p $base_path/$log_path
    mv $base_path/access.log $base_path/$log_path/access_$day.log
    #echo $base_path/$log_path/access_$day.log
    kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    Crontab 编辑定时任务
    01 00 * * * /xxx/path/autolog.sh  每天0时1分(建议在02-04点之间,系统负载小)
    
    • 1
    • 2

    5.Location

    5.1 概述

    location 有”定位”的意思, 根据Uri来进行不同的定位.
    在虚拟主机的配置中,是必不可少的,location可以把网站的不同部分,定位到不同的处理方式上.

    location 的语法:

    location [=|~|~*|^~] /uri/ { … }
    
    ^代表开头
    $代表结尾
    !代表否
    
    • 1
    • 2
    • 3
    • 4
    • 5
    - 精准匹配
    location = /uri/ {}
    - 一般(通用)匹配
    location /uri/ {}  
    - 正则匹配
    location ~ /uri/ {}     开头表示区分大小写的正则匹配   
    location !~ /uri/ {}    开头区分大小写不匹配
    location ~* /uri/ {}    开头表示不区分大小写的正则匹配       
    location !~* /uri/ {}   开头表示不区分大小写的正则不匹配       
    location ^~ /uri/ {}  开头表示uri以某个常规字符串开头,理解为匹配url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    5.2 匹陪步骤

    匹配步骤:

    1.先判断精准命中,如果命中,则返回结果并结束解析过程
    2.判断普通命中,如果有多个命中,则"记录"下来最长的命中结果(准备根据最长的命中结果返回)
    3.继续判断正则表达式的解析结果,按配置中的正则表达式顺序为准,由上到下开始匹配,一旦匹配成功1个,立即返回结果,并结束解析过程;

    总结:

    A.精准命中,立即返回;
    B.普通命中,无论顺序,按命中长短来确定;
    C.正则命中,顺序有所谓,谁先命中就是谁;

    5.3 示例

    location = / {
       #规则A
    }
    location = /login {
       #规则B
    }
    location ^~ /static/ {
       #规则C
    }
    location ~ \.(gif|jpg|png|js|css)$ {
       #规则D,注意:是根据括号内的大小写进行匹配。括号内全是小写,只匹配小写
    }
    location ~* \.png$ {
       #规则E
    }
    location !~ \.xhtml$ {
       #规则F
    }
    location !~* \.xhtml$ {
       #规则G
    }
    location / {
       #规则H
    }
    
    
    
    访问根目录/, 比如http://localhost/ 将匹配规则A
    
    访问 http://localhost/login 将匹配规则B,http://localhost/register 则匹配规则H
    
    访问 http://localhost/static/a.html 将匹配规则C
    
    访问 http://localhost/a.gif, http://localhost/b.png 将匹配规则D和规则E,但是规则D顺序优先,规则E不起作用, 而 http://localhost/static/c.png 则优先匹配到 规则C
    
    访问 http://localhost/a.PNG 则匹配规则E, 而不会匹配规则D,因为规则E不区分大小写。
    
    访问 http://localhost/a.xhtml 不会匹配规则F和规则G,
    
    访问 http://localhost/a.XHTML不会匹配规则G,(因为!)。规则F,规则G属于排除法,符合匹配规则也不会匹配到,所以想想看实际应用中哪里会用到。
    
    访问 http://localhost/category/id/1111 则最终匹配到规则H,因为以上规则都不匹配,这个时候nginx转发请求给后端应用服务器,比如FastCGI(php),tomcat(jsp),nginx作为方向代理服务器存在。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    https://www.cnblogs.com/jpfss/p/10232980.html

    5.4 配置示例

    实际使用中,一般至少有三个匹配规则定义

    #直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。
    #这里是直接转发给后端应用服务器了,也可以是一个静态首页
    # 1)第一个必选规则
    location = / {
        proxy_pass http://tomcat:8080/index
    }
     
    #2) 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项
    # 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用
    location ^~ /static/ {                              //以xx开头
        root /webroot/static/;
    }
    location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {     //以xx结尾
        root /webroot/res/;
    }
     
    #3) 第三个规则就是通用规则,用来转发动态请求到后端应用服务器
    #非静态文件请求就默认是动态请求,自己根据实际把握
    location / {
        proxy_pass http://tomcat:8080/
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    6.Rewrite

    6.1 概述

    • rewrite是实现URL重定向的重要指令,他根据regex(正则表达式)来匹配内容跳转到replacement,结尾是flag标记

    • 指令语法:rewrite regex replacement[flag]

    • 默认值:none

    • 应用位置:server、location、if

    • 作用场景:
      URL访问跳转,支持开发设计,如页面跳转,兼容性支持,展示效果等
      SEO优化
      维护:后台维护、流量转发等
      安全

    ## 关键字
    set #设置变量
    return #返回状态码 
    break #跳出rewrite
    rewrite #重写
    
    ## 常用语法
    If 空格 (条件) {
        重写模式
    }
    
    ## 条件语法
    1) “=”来判断相等, 用于字符串比较
    2) “~” 用正则来匹配(此处的正则区分大小写)
       ~* 不区分大小写的正则
    3) -f和!-f 用来判断是否存在文件
       -d和!-d 用来判断是否存在目录
       -e和!-e 用来判断是否存在文件或目录
       -x和!-x 用来判断文件是否可执行
    4) 正则
    \	将后面接着的字符标记为一个特殊字符或者一个原义字符或一个向后引用
    ^	匹配输入字符串的起始位置
    $	匹配输入字符串的结束位置
    *	匹配前面的字符零次或者多次
    +	匹配前面字符串一次或者多次
    ?	匹配前面字符串的零次或者一次
    .	匹配除“\n”之外的所有单个字符
    (pattern)	匹配括号内的pattern
    
    ## rewrite 最后一项flag参数:
    标记符号	说明
    last	本条规则匹配完成后继续向下匹配新的location URI规则
    break	本条规则匹配完成后终止,不在匹配任何规则
    redirect – 返回临时重定向的HTTP状态302
    permanent – 返回永久重定向的HTTP状态30
    
    
    ## 全局变量
    例:http://localhost:88/test1/test2/test.php
    1) $host:localhost
    2) $server_port:88
    3) $request_uri:http://localhost:88/test1/test2/test.php
    4) $document_uri:/test1/test2/test.php
    5) $document_root:D:\nginx/html
    6) $request_filename:D:\nginx/html/test1/test2/test.php
    
    ## 其它全局变量
     $args
     $content_length
     $content_type
     $document_root
     $document_uri
     $host
     $http_user_agent
     $http_cookie
     $limit_rate
     $request_body_file
     $request_method
     $remote_addr
     $remote_port
     $remote_user
     $request_filename
     $request_uri
     $query
     
    ## rewrite_log指令
    该指令用于是否开启URL重写日志的输出,
    语法:
      rewrite_log on | off
      默认是off,如果配置为on,URL重写的相关日志将以notice级别输出到error_log指令配置的日志文件中
    
    
    ## set指令
    
    用来设置新的变量,
      语法: set variable value;
        variable,这个是变量的名称,这个符号的“$”必须作为变量第一个字符,并且不能和Nginx服务器预设的全局变量同名
        value,为变量的值。
    比如 set $id “3”; #设置id为3
    
    
    ## uninitialized_variable_warn指令
    
    这个指令用来配置会用未初始化的变量时,是否记录警告日志,
     语法: unitialized_variable_warn on | off
      默认设置时on状态
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86

    6.2 示例

    示例1

    if  ($remote_addr = 192.168.1.100) {
                return 403;
            }
    
    if ($http_user_agent ~ MSIE) {
                    rewrite ^.*$ /ie.htm;
                    break; #(不break会循环重定向)
     }
    
    if (!-e $document_root$fastcgi_script_name) {
        rewrite ^.*$ /404.html break; ##注, 此处还要加break,
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    示例2

    例子一(域名跳转):
        server {
                listen 80;
                server_name   abc.com;
                rewrite   ^/(.*)     http://www.abc.com/$1 permanent;  # 跳转到www.abc.com网址上
            }
    例子二:
      server {
                listen 80;
                server_name   www.myweb.com www.web.info
                if($host ~ myweb\.info){                        #"."需要使用“\”转义,这里是匹配到www.web.info时
                         rewrite ^(.*)  http://www.myweb.com/&1 permanent;   #永久重定向到http://www.myweb.com网址上&1是匹配的uri
                }
            }
    例子三(防盗链):
    location ~* \.(gif|jpg|png|swf|flv)$ {
        valid_referers none blocked www.vison.com www.wsvison.com;  #这里表示Referer头域中的值是none或者blocked或者后面这些网址才会返回去正常的gif|jpg|png|swf|flv文件,否则执行下面if块代码
        if ($invalid_referer) {  #上面没有匹配成功,$invalid_referer值为1,否则为0
            return 404;
        } //防盗链
    }       
    其他例子:    
    if ($http_user_agent ~ MSIE) {
        rewrite ^(.*)$ /msie/$1 break;
    } //如果UA包含"MSIE",rewrite请求到/msid/目录下
    
    if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
        set $id $1;
     } //如果cookie匹配正则,设置变量$id等于正则引用部分
    
    if ($request_method = POST) {
        return 405;
    } //如果提交方法为POST,则返回状态405(Method not allowed)。return不能返回301,302
    
    if ($slow) {
        limit_rate 10k;
    } //限速,$slow可以通过 set 指令设置
    
    if (!-f $request_filename){
        break;
        proxy_pass  http://127.0.0.1; 
    } //如果请求的文件名不存在,则反向代理到localhost 。这里的break也是停止rewrite检查
    
    if ($args ~ post=140){
        rewrite ^ http://example.com/ permanent;
    } //如果query string中包含"post=140",永久重定向到example.com
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    set 使用示例

    if ($http_user_agent ~* msie) {
                    set $isie 1;
    }
    
    if ($fastcgi_script_name = ie.html) {
        set $isie 0;
    }
    
    if ($isie 1) {
        rewrite ^.*$ ie.html;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6.3 注意

    • 服务器内部的rewrite和302跳转不一样.
      跳转的话URL都变了,变成重新http请求404.html, 而内部rewrite, 上下文没变
    • 用url重写时, 正则里如果有”{}”,正则要用双引号包起来

    7.gzip

    http://nginx.org/en/docs/http/ngx_http_gzip_module.html

    7.1 抓包查看

    • 请求:
      Accept-Encoding:gzip,deflate,sdch
    • 响应:
      Content-Encoding:gzip
      Content-Length:36093
    • 分析: 再把页面另存下来,观察,约10W字节,实际传输的35093字节,原因-------就在于gzip压缩上.
    • 压缩节省带宽

    7.2 原理

    浏览器---请求----> 声明可以接受 gzip压缩 或 deflate压缩 或compress 或 sdch压缩
    从http协议的角度看--请求头 声明 acceopt-encoding: gzip deflate sdch  (是指压缩算法,其中sdch是google倡导的一种压缩方式,目前支持的服务器尚不多)
    服务器-->回应---把内容用gzip方式压缩---->发给浏览器
    浏览<-----解码gzip-----接收gzip压缩内容----
    
    • 1
    • 2
    • 3
    • 4

    7.3 常用参数

    gzip on|off;  #是否开启gzip
    gzip_buffers 32 4K| 16 8K #缓冲(压缩在内存中缓冲多少块? 每块大小为多少?)
    gzip_comp_level [1-9] #推荐6 压缩级别(级别越高,压的越小,越浪费CPU计算资源)
    gzip_disable #正则匹配 什么样的Uri不进行gzip
    gzip_min_length 200 # 开始压缩的最小长度(再小就不要压缩了,用处不大)
    gzip_http_version 1.0|1.1 # 开始压缩的http协议版本(可以不设置,目前几乎全是1.1协议)
    gzip_proxied          # 设置请求者代理服务器,该如何缓存内容
    gzip_types text/plain  application/xml # 对哪些类型的文件用压缩 如txt,xml,html ,css
    gzip_vary on|off  # 是否传输gzip压缩标志
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    7.4 示例

    server{
        ### 开启gzip
        gzip on;
        # 设置压缩所需要的缓冲区大小     
        gzip_buffers 32 4K;
        gzip_comp_level 6;
        #启用gzip压缩的最小文件,小于设置值的文件将不会压缩
        gzip_min_length 1k;
        # 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。
        gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png application/vnd.ms-fontobject font/ttf font/opentype font/x-woff image/svg+xml;
         # 是否在http header中添加Vary: Accept-Encoding,建议开启
        gzip_vary on;
        # 禁用IE 6 gzip
        gzip_disable "MSIE [1-6]\.";
        # 设置gzip压缩针对的HTTP协议版本
        gzip_http_version 1.0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    7.4 注意

    • 图片/mp3这样的二进制文件,不必压缩,因为压缩也是耗费CPU资源的
    • 比较小的文件不必压缩,
    • gx_http_gzip_module是Nginx默认集成的,不需要重新编译,直接开启即可

    8.expires

    8.1 expires概述

    nginx的缓存设置,提高网站性能;一些网站的图片,比如新闻站, 图片发布后改动的可能非常小.我们希望 能否在用户访问一次后, 图片缓存在用户的浏览器端,且时间比较长的缓存.

    对于变化周期较短的,如静态html,js,css,比较适于用这个方式

    8.2格式

    在location或if段里中

     expires 30s;
     expires 30m;
     expires 2h;
     expires 30d;
    
    • 1
    • 2
    • 3
    • 4

    (注意:服务器的日期要准确,如果服务器的日期落后于实际日期,可能导致缓存失效)

        location ~ \.(jpg|jpeg|png|gif)$ {
                expires 1d;
            }
            location ~ \.js$ {
               expires 1h;
            }
            
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    8.3 原理

    服务器响应文件内容同时响应2个标签:

    1. etag标签(内容的签名,随着内容改变而改变)
    2. last_modified_since 2个标签值

    浏览器下次去请求时,头信息发送这两个标签, 服务器检测文件是否有变化,如无,直接头信息返回 etag,last_modified_since,浏览器知道内容无改变,于是直接调用本地缓存.

    这个过程,虽然也请求了服务器,但是传着的内容极少.

    9.反向代理服务器+负载均衡

    9.1 负载均衡

    负载均衡是一种方案,实现办法有DNS轮询,

    把图片重写到 8080端口(既然能写到8080端口,就意味着可以写到其他独立服务器上)
            location ~ \.(jpg|jpeg|png|gif)$ {
                    proxy_pass http://192.168.1.204:8080;
                    expires 1d;
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    10 参考

    https://www.cnblogs.com/jpfss/p/10232980.html

  • 相关阅读:
    ClickHouse联合创始人、前Google副总裁Yury到访杭州玖章算术公司,双方建立生态合作
    SpringCloud和SpringBoot在调Feign传文件时的异常汇总及解决办法
    社交媒体&社交商务提升策略,看这一篇就够!
    OB Cloud助力泡泡玛特打造新一代分布式抽盒机系统
    栈和队列的基本使用
    javaweb高校实验室管理系统ssm
    ViewBinding 初探-在Activity和Adapter中使用
    通用/参考电路/ 连接备份
    RabbitMq
    【图形学】20 基础纹理(一、单张纹理)
  • 原文地址:https://blog.csdn.net/bobshute/article/details/128029090