Nginx基础之动静分离/防盗链/重定向/location/日志/平滑升级

10、nginx 实现动静分离

为了加快网站的解析速度,可以把动态页面和静态页面由不同的服务器来解析,加快解析速度。降低原来单个服务器的压力。 在动静分离的tomcat的时候比较明显,因为tomcat解析静态很慢,其实这些原理的话都很好理解,简单来说,就是使用正则表达式匹配过滤,然后交个不同的服务器。

1、准备环境

准备一个nginx代理 两个http 分别处理动态和静态。

location / {
            root   /var/www/html/upload;
            index  index.php index.htm;
        }

2、本地配置

location ~ .*\.(html|gif|jpg|png|bmp|swf|jpeg)$ {
            root   /var/www/html/static;
            index  index.html;
        }
  location ~ \.php$ {
            root   /var/www/html/move;
            index  index.php;
        }

3、代理配置

location ~ .*\.(html|gif|jpg|png|bmp|swf|jpeg)$ {
                proxy_pass http://172.17.14.3:80;
        }
  location ~ \.php$ {
                proxy_pass http://172.17.14.2:80;
        }

4、配置项说明

location / 的作用
定义了请求代理的时候nginx去/var/www/html/upload 下寻找index.php 当他找到index.php的时候匹配了下面的正则 location ~ .php$。

location ~ .php$ 的作用
以php结尾的都以代理的方式转发给web1(172.17.14.2),http1 去处理,这里http1要去看自己的配置文件 在自己的配置文件中定义网站根目录 /var/www/html/upload 找.index.php 然后处理解析返回给nginx 。

location ~ .*.(html|gif|jpg|png|bmp|swf|jpeg)$ 的作用
以html等等的静态页面都交给web2(172.17.14.3)来处理 ,web2 去找自己的网站目录 然后返回给nginx 。

两个 web 放的肯定是一样的目录,只不过每个服务器的任务不一样。

代理本身要有网站的目录,因为最上面的 location / 先生效 如果没有目录 会直接提示找不到目录 不会再往下匹配。

11、nginx 防盗链问题

1、nginx 防止网站资源被盗用模块

ngx_http_referer_module

HTTP Referer是Header的一部分,当浏览器向Web服务器发送请求的时候,一般会带上Referer,

告诉服务器我是从哪个页面链接过来的,服务器借此可以获得一些信息用于处理,例如防止未经允许

的网站盗链图片、文件等。因此HTTP Referer头信息是可以通过程序来伪装生成的,所以通过Referer

信息防盗链并非100%可靠,但是,它能够限制大部分的盗链情况。

2. 防盗链配置

配置要点:

# 日志格式添加"$http_referer"
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                         '$status $body_bytes_sent "$http_referer" '
                         '"$http_user_agent" "$http_x_forwarded_for"';
# valid_referers 使用方式                         
Syntax: 	valid_referers none | blocked | server_names | string ...;
Default: 	—
Context: server, location
  • none : 允许没有http_refer的请求访问资源;
  • blocked : 允许不是http://开头的,不带协议的请求访问资源;
  • server_names : 只允许指定ip/域名来的请求访问资源(白名单);
[root@localhost ~]# vim /etc/nginx/conf.d/nginx.conf
        location / {
                root /usr/share/nginx/html;
                index index.html index.htm;

                valid_referers  *.qf.com 192.168.19.135;
                if ($invalid_referer) {
                   return 403;
                }
        }


[root@localhost ~]# vim /etc/nginx/conf.d/nginx.conf
        location ~ .*\.(gif|jpg|png|jpeg)$ {
                root  /usr/share/nginx/html;                  
                valid_referers none blocked qf.com 192.168.19.135;
                if ($invalid_referer) {
                    return 403;
                }
         }

页面配置

qf.com
[root@localhost ~]# vim /var/www/html/index.html                           
<html>
<head>
    <meta charset="utf-8">
    <title>qf.com</title>
</head>
<body style="background-color:red;">
    <img src="http://192.168.19.135/nginx-logo.png"/>
</body>
</html>

3、 重载nginx服务

[root@localhost ~]# nginx -s reload -c /etc/nginx/nginx.conf

4、 测试防盗链

1、不带http_refer

[root@localhost ~]# curl -I http://192.168.19.135/qf.jpg
HTTP/1.1 200 OK
Server: nginx/1.14.1
Date: Thu, 30 Nov 2018 18:26:10 GMT
Content-Type: image/jpeg
Content-Length: 68227
Last-Modified: Thu, 30 Nov 2018 17:46:19 GMT
Connection: keep-alive
ETag: "5a2043eb-10a83"
Accept-Ranges: bytes

2、带非法http_refer

[root@localhost ~]# curl -e "http://www.baidu.com" -I http://192.168.19.135/nginx-logo.png
HTTP/1.1 403 Forbidden
Server: nginx/1.14.1
Date: Thu, 30 Nov 2018 18:25:52 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

3 带合法http_refer

[root@localhost ~]# curl -e "http://192.168.95.135" -I http://192.168.95.135/nginx-logo.png
HTTP/1.1 200 OK
Server: nginx/1.14.1
Date: Thu, 30 Nov 2018 18:27:30 GMT
Content-Type: image/jpeg
Content-Length: 68227
Last-Modified: Thu, 30 Nov 2018 17:46:19 GMT
Connection: keep-alive
ETag: "5a2043eb-10a83"
Accept-Ranges: bytes

5、其他配置

1、匹配域名

完全防盗
location ~ .*\.(gif|jpg|png|jpeg)$ {
    valid_referers 192.168.95.134 *.baidu.com *.google.com;
    if ($invalid_referer) {
        rewrite ^/ http://192.168.95.134/fdl.jpg
        #return 403;
    }
    root  /var/www/html/images;
}
直接访问图片链接可以下载
location ~* \.(gif|jpg|png|bmp)$ {
       valid_referers none blocked  *.qf.com  ~tianyun  ~\.google\./ ~\.baidu\./;
       if ($invalid_referer) {
           return 403;
           #rewrite .* http://qf.com/403.jpg;
    }
}

以上所有来自 qf.com 和域名中包含google和baidu的站点都可以访问到当前站点的图片,如果来源域名不在这个列表中,那么$invalid_referer等于1,在if语句中返回一个403给用户,这样用户便会看到一个403的页面,如果使用下面的rewrite,那么盗链的图片都会显示403.jpg。如果用户直接在浏览器输入你的图片地址,那么图片显示正常,因为它符合none这个规则。

防盗链配置过程演示

先准备两台机器.A机器放个图片,B机器配置去盗A机器的图片.

[root@tnt-1 ~]# wget http://www.dzwww.com/yule/yulezhuanti/mtcbg/201507/W020150714364226659071.jpg
[root@tnt-1 ~]# mv W020150714364226659071.jpg 1.jpg
[root@tnt-1 ~]# mv 1.jpg /usr/share/nginx/html/

[root@tnt-1 ~]# vim /etc/nginx/nginx.conf
 location / {
        valid_referers none blocked *.tntnb.vip;
                if ($invalid_referer) {
                   return 403;
                }
        }

#A服务下载个图片.
#把图片名改为1.jpg,方便操作.
#把图片移到根目录.
#修改配置文件.
#location里面加入防盗链模块.
#none blocked *.tntnb.vip 这里的意思是只允许匹配tntnb.vip这个域名的*.去调用这个图片.加什么允许什么等于过白.

[root@tnt-2 ~]# vim /usr/share/nginx/html/index.html
<html>
<head>
    <meta charset="utf-8">
    <title>qf.com</title>
</head>
<body style="background-color:red;">
    <img src="http://120.25.217.xxx/1.jpg"/>
</body>
</html>

[root@tnt-2 ~]# nginx -s reload
#去B服务器改下首页内容.把里面的文件链接改成刚才A机器里面的图片路径.
#重新加载.
#然后用浏览器去访问检测.

在这里插入图片描述
直接浏览器访问B机器的IP,发现调用不了A机器的IP.
此时A机器的防盗链模块里面并没有给B机器的IP加白.
location / {
valid_referers none *.tntnb.vip;
if ($invalid_referer) {
return 403;
}
}
然后把B机器的IP给加上之后再次用浏览器访问测试. 成功.
location / {
valid_referers none *.tntnb.vip 182.61.13.xx;
if ($invalid_referer) {
return 403;
}
}
在这里插入图片描述

[root@tnt-1 ~]# vim /etc/nginx/nginx.conf
 location / {
        valid_referers none *.tntnb.vip;
                if ($invalid_referer) {
                   return 403;
                }
        }
[root@tnt-1 ~]# nginx -s reload        
#此时回去再看一下A机器的模块内容,把B机器的IP删掉,用另外一种方式检测.
#重新加载

[root@tnt-2 ~]# curl -I http://120.25.217.xxx/1.jpg
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Thu, 21 May 2020 17:20:49 GMT
Content-Type: image/jpeg
Content-Length: 59358
Last-Modified: Tue, 14 Jul 2015 02:53:15 GMT
Connection: keep-alive
ETag: "55a4799b-e7de"
Accept-Ranges: bytes

[root@tnt-2 ~]# curl -e "http://www.baidu.com" -I http://120.25.217.xxx/1.jpg
HTTP/1.1 403 Forbidden
Server: nginx/1.16.1
Date: Thu, 21 May 2020 17:20:56 GMT
Content-Type: text/html
Content-Length: 153
Connection: keep-alive

[root@tnt-2 ~]# curl -e "http://www.tntnb.vip" -I http://120.25.217.xxx/1.jpg
HTTP/1.1 200 OK
Server: nginx/1.16.1
Date: Thu, 21 May 2020 17:21:02 GMT
Content-Type: image/jpeg
Content-Length: 59358
Last-Modified: Tue, 14 Jul 2015 02:53:15 GMT
Connection: keep-alive
ETag: "55a4799b-e7de"
Accept-Ranges: bytes

#上面这三个分别是.
#不带请求头.
#带违法请求头.
#带合法请求头.

182.61.xx.xx - - [22/May/2020:01:20:49 +0800] "HEAD /1.jpg HTTP/1.1" 200 0 "-" "curl/7.29.0" "-"
182.61.xx.xx - - [22/May/2020:01:20:56 +0800] "HEAD /1.jpg HTTP/1.1" 403 0 "http://www.baidu.com" "curl/7.29.0" "-"
182.61.xx.xx - - [22/May/2020:01:21:02 +0800] "HEAD /1.jpg HTTP/1.1" 200 0 "http://www.tntnb.vip" "curl/7.29.0" "-"
#这三条是A机器对应上面三条请求的日志记录.

12、nginx 地址重写 rewrite

1、什么是Rewrite

Rewrite对称URL Rewrite,即URL重写,就是把传入Web的请求重定向到其他URL的过程。

  • URL Rewrite最常见的应用是URL伪静态化,是将动态页面显示为静态页面方式的一种技术。比如
    http://www.123.com/news/index.php?id=123 使用URLRewrite 转换后可以显示为 http://www.123
    .com/news/123.html对于追求完美主义的网站设计师,就算是网页的地址也希望看起来尽量简洁明快。
    理论上,搜索引擎更喜欢静态页面形式的网页,搜索引擎对静态页面的评分一般要高于动态页面。所
    以,UrlRewrite可以让我们网站的网页更容易被搜索引擎所收录。

  • 从安全角度上讲,如果在URL中暴露太多的参数,无疑会造成一定量的信息泄漏,可能会被一些黑客
    利用,对你的系统造成一定的破坏,所以静态化的URL地址可以给我们带来更高的安全性。

  • 实现网站地址跳转,例如用户访问360buy.com,将其跳转到jd.com。例如当用户访问tianyun.com的
    80端口时,将其跳转到443端口。

2、Rewrite 相关指令

Nginx Rewrite 相关指令有 if、rewrite、set、return

1、if 语句

应用环境

server,location

语法
if (condition) {}
if 可以支持如下条件判断匹配符号
~ 					正则匹配 (区分大小写)
~* 				    正则匹配 (不区分大小写)
!~                  正则不匹配 (区分大小写)
!~*		            正则不匹配  (不区分大小写)
-f 和!-f 		    用来判断是否存在文件
-d 和!-d 		    用来判断是否存在目录
-e 和!-e 		    用来判断是否存在文件或目录
-x 和!-x 		    用来判断文件是否可执行

在匹配过程中可以引用一些Nginx的全局变量
$args				请求中的参数;
$document_root	    针对当前请求的根路径设置值;
$host				请求信息中的"Host",如果请求中没有Host行,则等于设置的服务器名;
$limit_rate			对连接速率的限制;
$request_method		请求的方法,比如"GET""POST";
$remote_addr		客户端地址;
$remote_port		客户端端口号;
$remote_user		客户端用户名,认证用;
$request_filename   当前请求的文件路径名(带网站的主目录/usr/local/nginx/html/images /a.jpg)
$request_uri		当前请求的文件路径名(不带网站的主目录/images/a.jpg)
$query_string$args相同;
$scheme				用的协议,比如http或者是https
$server_protocol	请求的协议版本,"HTTP/1.0""HTTP/1.1";
$server_addr 		服务器地址,如果没有用listen指明服务器地址,使用这个变量将发起一次系统调用以取得地址(造成资源浪费);
$server_name		请求到达的服务器名;
$document_uri$uri一样,URI地址;
$server_port 		请求到达的服务器端口号;

2、Rewrite flag

rewrite 指令根据表达式来重定向URI,或者修改字符串。可以应用于server,location, if环境下每行rewrite指令最后跟一个flag标记,支持的flag标记有:

last 			    相当于Apache里的[L]标记,表示完成rewrite
break 				本条规则匹配完成后,终止匹配,不再匹配后面的规则
redirect 			返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent 		    返回301永久重定向,浏览器地址会显示跳转后URL地址

redirect 和 permanent区别则是返回的不同方式的重定向,对于客户端来说一般状态下是没有区别的。而对于搜索引擎,相对来说301的重定向更加友好,如果我们把一个地址采用301跳转方式跳转的话,搜索引擎会把老地址的相关信息带到新地址,同时在搜索引擎索引库中彻底废弃掉原先的老地址。使用302重定向时,搜索引擎(特别是google)有时会查看跳转前后哪个网址更直观,然后决定显示哪个,如果它觉的跳转前的URL更好的话,也许地址栏不会更改,那么很有可能出现URL劫持的现像。在做URI重写时,有时会发现URI中含有相关参数,如果需要将这些参数保存下来,并且在重写过程中重新引用,可以用到 () 和 $N 的方式来解决。

3、Rewrite匹配参考示例

示例1:
# http://www.tianyun.com/a/1.html ==> http://www.tianyun.com/b/2.html
location /a {
    rewrite .* /b/2.html permanent;
    #return 301 /b/2.html;
}

例2:
# http://www.tianyun.com/2019/a/1.html ==> http://www.tianyun.com/2018/a/1.html
location /2019 {
     rewrite ^/2019/(.*)$ /2018/$1 permanent;
}
例3:
# http://www.qf.com/a/1.html ==> http://jd.com
if ( $host ~* qf.com ) {
	rewrite .*	http://jd.com permanent;
}

例4:
# http://www.qf.com/a/1.html ==> http://jd.com/a/1.html
if ( $host ~* qf.com ) {
	rewrite  .*	 http://jd.com$request_uri permanent;
}

例5: 在访问目录后添加/  (如果目录后已有/,则不加/)
# http://www.tianyun.com/test/
# $1: /a/b
# $2: c
# http://$host$1$2/
if (-d $request_filename) {
    rewrite ^(.*)([^/])$ http://$host$1$2/ permanent;
}

例6:
# http://www.tianyun.com/login/tianyun.html ==>  http://www.tianyun.com/reg/login.php?user=tianyun

location /login {
           rewrite ^/login/(.*)\.html$ /reg/login.php?user=$1;
        }

例7:
#http://www.tianyun.com/qf/11-22-33/1.html  ==>  http://www.tianyun.com/qf/11/22/33/1.html
location /qf {
            rewrite ^/qf/([0-9]+)-([0-9]+)-([0-9]+)(.*)$ /qf/$1/$2/$3$4 permanent;
        }
例子演示
例1

# http://1.1.1.1/a/1.html ==> http://1.1.1.1/b/2.html

[root@tnt-1 ~]# vim /etc/nginx/nginx.conf 
location /a {
    rewrite .* /b/2.html permanent;
    }
#打开配置文件
#加入两行参数,设置a跳转到b.并且是permanent 301重定向.

[root@tnt-1 ~]# cd /usr/local/nginx/html/

[root@tnt-1 html]# mkdir a b

[root@tnt-1 html]# ls
50x.html  a  b  index.html

[root@tnt-1 html]# echo "a/1.html" > a/1.html
[root@tnt-1 html]# echo "b/2.html" > b/2.html

#进入到默认访问的主目录.
#根据例子需求,创建两个文件夹以及两个文件.

[root@tnt-1 html]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@tnt-1 html]# nginx -s reload

#检查配置文件.
#重新加载.
#然后浏览器访问检查.

在这里插入图片描述

例2

# http://1.1.1.1/2019/a/1.html ==> http://1.1.1.1/2018/a/1.html

[root@tnt-1 html]# vim /etc/nginx/nginx.conf
        location /2019 {
                rewrite ^/2019/(.*)$ /2018/$1 permanent;
                }
                
[root@tnt-1 html]# ls
50x.html  a  b  index.html

[root@tnt-1 html]# rm -rf a b


#打开配置文件.
#加入重定向模块.
#删掉上一次实验的ab目录

[root@tnt-1 html]# mkdir -pv 2018/a
mkdir: 已创建目录 "2018"
mkdir: 已创建目录 "2018/a"

[root@tnt-1 html]# echo "2018/a/1.html" > 2018/a/1.html
[root@tnt-1 html]# echo "2018/a/2.html" > 2018/a/2.html
[root@tnt-1 html]# echo "2018/a/3.html" > 2018/a/3.html

[root@tnt-1 html]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@tnt-1 html]# nginx -s reload

#因为最终是要请求2018/a下面的内容.
#所以要创建2018/a/xxx.html出来.
#检查
#重加载.
#最后浏览器访问检测.

#这个例子用到了变量和正则匹配.
#只要匹配到以^/2019开头的/(.*)$任意字符路径,都会重定向到/2018/开头,并且把前面输入的参数也传递过来$1.

在这里插入图片描述

4、set 指令

set 指令是用于定义一个变量,并且赋值
应用环境:

server,location,if

应用示例

例8:
#http://alice.tianyun.com ==> http://www.tianyun.com/alice
#http://jack.tianyun.com ==> http://www.tianyun.com/jack

[root@localhost html]# mkdir jack alice
[root@localhost html]# echo jack.... > jack/index.html
[root@localhost html]# echo alice... > alice/index.html

a. DNS实现泛解析
*   		IN      A			    网站IP

b. nginx Rewrite
if ($host ~* "^www.tianyun.com$" ) {
      break;
  }

if ($host ~* "^(.*)\.tianyun\.com$" ) {
      set $user $1;
      rewrite .* http://www.tianyun.com/$user permanent;
  }

5、return 指令

return 指令用于返回状态码给客户端

应用环境:
server,location,if

应用示例:

例9:如果访问的.sh结尾的文件则返回403操作拒绝错误
location ~* \.sh$ {
	return 403;
	#return 301 http://www.tianyun.com;
}

例10:80 ======> 443
server {
        listen      80;
        server_name  www.tianyun.com tianyun.com;
        return     301  https://www.tianyun.com$request_uri;
        }
server {
        listen      443 ssl;
        server_name  www.tianyun.com;
        ssl  on;
        ssl_certificate      /usr/local/nginx/conf/cert.pem;
        ssl_certificate_key  /usr/local/nginx/conf/cert.key;
        location / {
            root html;
            index index.html index.php;
        }
    }

[root@localhost html]# curl -I http://www.tianyun.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.1
Date: Tue, 26 Jul 2016 15:07:50 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: https://www.tianyun.com/

3、last,break详解

在这里插入图片描述

location / {
    root /usr/share/nginx/html;
    index index.html;
}
   location /break/ {
    root /usr/share/nginx/html;
    rewrite .* /test/break.html break;
}

  location /last/ {
   root /usr/share/nginx/html;
   rewrite .* /test/last.html last;
}

  location /test/ {
   root /usr/share/nginx/html;
   rewrite  .* /test/test.html break ;

}
!!!注意上一步实验 https缓存影响


[root@localhost html]# mkdir test
[root@localhost html]# echo 'break' > test/break.html
[root@localhost html]# echo 'last' > test/last.html
[root@localhost html]# echo 'test...' > test/test.html

http://192.168.10.33/break/break.html
http://192.168.10.33/last/last.html

注意:

  • last 标记在本条 rewrite 规则执行完后,会对其所在的 server { … } 标签重新发起请求;

  • break 标记则在本条规则匹配完成后,停止匹配,不再做后续的匹配;

  • 使用 alias 指令时,必须使用 last;

  • 使用 proxy_pass 指令时,则必须使用break。

4、Nginx 的 https ( rewrite )

server {
        listen       80;
        server_name  *.vip9999.top vip9999.top;

        if ($host ~* "^www.vip9999.top$|^vip9999.top$" ) {
                return 301 https://www.vip9999.top$request_uri;
        }

        if ($host ~* "^(.*).vip9999.top$" ) {
                set $user $1;
                return 301 https://www.vip9999.top/$user;
        }

    }

    # Settings for a TLS enabled server.
    server {
        listen       443 ssl;
        server_name  www.vip9999.top;

        location / {
                root      /usr/share/nginx/html;
                index     index.php index.html;
        }

        #pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        location ~ \.php$ {
            root           /usr/share/nginx/html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
        ssl on;
        ssl_certificate cert/214025315060640.pem;
        ssl_certificate_key cert/214025315060640.key;
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;
        }

5、Apache 的 https ( rewrite )

[root@localhost ~]# yum -y install httpd mod_ssl
[root@localhost ~]# vim /etc/httpd/conf.d/vip9999.conf

在这里插入图片描述

13、nginx location 指令详解

Nginx 的 HTTP 配置主要包括三个区块,结构如下:

http { 						# 这个是协议级别
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 65;
  gzip on;
    server {			 # 这个是服务器级别
      listen 80;
      server_name localhost;
        location / {  # 这个是请求级别
          root html;
          index index.html index.htm;
        }
      }
}

1、location 区段

  • location 是在 server 块中配置,根据不同的 URI 使用不同的配置,来处理不同的请求。

  • location 是有顺序的,会被第一个匹配的location 处理。

  • 基本语法如下:

location [=|~|~*|^~|@] pattern{……}

2、location 前缀含义

=    表示精确匹配,优先级也是最高的 
^~   表示uri以某个常规字符串开头,理解为匹配url路径即可 
~    表示区分大小写的正则匹配  
~*   表示不区分大小写的正则匹配
!~   表示区分大小写不匹配的正则
!~*  表示不区分大小写不匹配的正则
/    通用匹配,任何请求都会匹配到
@    内部服务跳转

3、location 配置示例

1、没有修饰符 表示:必须以指定模式开始

server {
  server_name qf.com;
  location /abc {
    ……
  }
}

那么,如下是对的:
http://qf.com/abc
http://qf.com/abc?p1
http://qf.com/abc/
http://qf.com/abcde 

2、=表示:必须与指定的模式精确匹配

server {
server_name qf.com
  location = /abc {
    ……
  }
}
那么,如下是对的:
http://qf.com/abc
http://qf.com/abc?p1
如下是错的:
http://qf.com/abc/
http://qf.com/abcde

3、~ 表示:

指定的正则表达式要区分大小写

server {
server_name qf.com;
  location ~ ^/abc$ {
    ……
  }
}
那么,如下是对的:
http://qf.com/abc
http://qf.com/abc?p1=11&p2=22
如下是错的:
http://qf.com/ABC
http://qf.com/abc/
http://qf.com/abcde

4、~* 表示:

指定的正则表达式不区分大小写

server {
server_name qf.com;
location ~* ^/abc$ {
    ……
  }
}
那么,如下是对的:
http://qf.com/abc
http://qf..com/ABC
http://qf..com/abc?p1=11&p2=22
如下是错的:
http://qf..com/abc/
http://qf..com/abcde

5、^~表示 :

类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,那么就停止搜索其他模式了。

6、@ 表示:

定义命名 location 区段,这些区段客户段不能访问,只可以由内部产生的请求来访问,如try_files或error_page等

location 区段匹配示例

location = / {
  # 只匹配 / 的查询.
  [ configuration A ]
}
location / {
  # 匹配任何以 / 开始的查询,但是正则表达式与一些较长的字符串将被首先匹配。
  [ configuration B ]
}
location ^~ /images/ {
  # 匹配任何以 /images/ 开始的查询并且停止搜索,不检查正则表达式。
  [ configuration C ]
}
location ~* \.(gif|jpg|jpeg)$ {
  # 匹配任何以gif, jpg, or jpeg结尾的文件,但是所有 /images/ 目录的请求将在Configuration C中处理。
  [ configuration D ]
} 
各请求的处理如下例:
	/ → configuration A
	/documents/document.html → configuration B
	/images/1.gif → configuration C
	/documents/1.jpg → configuration D

4、root 、alias 指令区别

location /img/ {
    alias /var/www/image/;
}
#若按照上述配置的话,则访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件
location /img/ {
    root /var/www/image;
}
#若按照这种配置的话,则访问/img/目录下的文件时,nginx会去/var/www/image/img/目录下找文件。] 
  • alias 是一个目录别名的定义,

  • root 则是最上层目录的定义。

  • 还有一个重要的区别是alias后面必须要用“/”结束,否则会找不到文件的,而root则可有可无。

14、nginx 日志配置

1、nginx 日志介绍

nginx 有一个非常灵活的日志记录模式,每个级别的配置可以有各自独立的访问日志, 所需日志模块 ngx_http_log_module 的支持,日志格式通过 log_format 命令来定义,日志对于统计和排错是非常有利的,下面总结了 nginx 日志相关的配置 包括 access_loglog_formatopen_log_file_cachelog_not_foundlog_subrequestrewrite_logerror_log

2、access_log 指令

访问日志主要记录客户端的请求。客户端向 Nginx 服务器发起的每一次请求都记录在这里。客户端IP,浏览器信息,referer,请求处理时间,请求URL等都可以在访问日志中得到。当然具体要记录哪些信息,你可以通过log_format指令定义。

语法:

# 设置访问日志
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
# 关闭访问日志
access_log off; 
  • path 指定日志的存放位置。
  • format 指定日志的格式。默认使用预定义的combined
  • buffer 用来指定日志写入时的缓存大小。默认是64k。
  • gzip 日志写入前先进行压缩。压缩率可以指定,从1到9数值越大压缩比越高,同时压缩的速度也越慢。默认是1。
  • flush 设置缓存的有效时间。如果超过flush指定的时间,缓存中的内容将被清空。
  • if 条件判断。如果指定的条件计算为0或空字符串,那么该请求不会写入日志。

作用域:

可以应用access_log指令的作用域分别有httpserverlocationlimit_except。也就是说,在这几个作用域外使用该指令,Nginx会报错。

基本用法:

access_log /var/logs/nginx-access.log

该例子指定日志的写入路径为/var/logs/nginx-access.log,日志格式使用默认的combined

access_log /var/logs/nginx-access.log buffer=32k gzip flush=1m

该例子指定日志的写入路径为/var/logs/nginx-access.log,日志格式使用默认的combined,指定日志的缓存大小为 32k,日志写入前启用 gzip 进行压缩,压缩比使用默认值 1,缓存数据有效时间为1分钟。

3、log_format 指令

Nginx 预定义了名为 combined 日志格式,如果没有明确指定日志格式默认使用该格式:

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

如果不想使用Nginx预定义的格式,可以通过log_format指令来自定义。

语法:

log_format name [escape=default|json] string ...;
  • name 格式名称。在 access_log 指令中引用。
  • escape 设置变量中的字符编码方式是json还是default,默认是default
  • string 要定义的日志格式内容。该参数可以有多个。参数中可以使用Nginx变量。

log_format` 指令中常用的一些变量:
在这里插入图片描述

自定义日志格式的使用:

access_log /var/logs/nginx-access.log main

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指令定义了一个main的格式,并在access_log指令中引用了它。假如客户端有发起请求:https://qf.com/,我们看一下我截取的一个请求的日志记录:

192.168.95.134 - - [20/Feb/2019:12:12:14 +0800] "GET / HTTP/1.1" 200 190 "-" "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Mobile Safari/537.36" "-"

我们看到最终的日志记录中$remote_user$http_referer$http_x_forwarded_for都对应了一个-,这是因为这几个变量为空。

4、error_log 指令

错误日志在Nginx中是通过error_log指令实现的。该指令记录服务器和请求处理过程中的错误信息。

语法
配置错误日志文件的路径和日志级别。

error_log file [level];
Default:	
error_log logs/error.log error;

file 参数指定日志的写入位置。

level 参数指定日志的级别。level可以是debug, info, notice, warn, error, crit, alert,emerg中的任意值。可以看到其取值范围是按紧急程度从低到高排列的。只有日志的错误级别等于或高于level指定的值才会写入错误日志中。默认值是error

基本用法

error_log /var/logs/nginx/nginx-error.log

配置段:mainhttp, mail, stream, server, location作用域。

例子中指定了错误日志的路径为:/var/logs/nginx/nginx-error.log,日志级别使用默认的 error

5、open_log_file_cache 指令

每一条日志记录的写入都是先打开文件再写入记录,然后关闭日志文件。如果你的日志文件路径中使用了变量,如 access_log /var/logs/$host/nginx-access.log,为提高性能,可以使用open_log_file_cache指令设置日志文件描述符的缓存。

语法

open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];

默认值: 
open_log_file_cache off;
  • max 设置缓存中最多容纳的文件描述符数量,如果被占满,采用LRU算法将描述符关闭。
  • inactive 设置缓存存活时间,默认是10s。
  • min_usesinactive时间段内,日志文件最少使用几次,该日志文件描述符记入缓存,默认是1次。
  • valid:设置多久对日志文件名进行检查,看是否发生变化,默认是60s。
  • off:不使用缓存。默认为off。

基本用法

open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

配置段:httpserverlocation作用域中。

例子中,设置缓存最多缓存1000个日志文件描述符,20s内如果缓存中的日志文件描述符至少被被访问2次,才不会被缓存关闭。每隔1分钟检查缓存中的文件描述符的文件名是否还存在。

6、log_not_found 指令

是否在error_log中记录不存在的错误。默认是
基本语法:

log_not_found on | off;
默认值: 
log_not_found on;

配置段: http, server, location作用域。

7、log_subrequest 指令

是否在access_log中记录子请求的访问日志。默认不记录
基本语法:

log_subrequest on | off;

默认值: 
log_subrequest off;

配置段: http, server, location作用域。

8、rewrite_log 指令

ngx_http_rewrite_module模块提供的。用来记录重写日志的。对于调试重写规则建议开启,启用时将在error log中记录notice级别的重写日志。

基本语法:

rewrite_log on | off;

默认值: 
rewrite_log off;

配置段: http, server, location, if作用域。

9、nginx 日志配置总结

Nginx中通过access_logerror_log指令配置访问日志和错误日志,通过log_format我们可以自定义日志格式。如果日志文件路径中使用了变量,我们可以通过open_log_file_cache 指令来设置缓存,提升性能。其他的根据自己的使用场景定义。

详细的日志配置信息可以参考Nginx官方文档

15、nginx 的平滑升级(了解)

1、为什么要对 nginx 平滑升级

随着 nginx 越来越流行,并且 nginx 的优势也越来越明显,nginx 的版本迭代也来时加速模式,1.9.0版本的nginx更新了许多新功能,例如 stream 四层代理功能,伴随着 nginx 的广泛应用,版本升级必然越来越快,线上业务不能停,此时 nginx 的升级就是运维的工作了

nginx 方便地帮助我们实现了平滑升级。其原理简单概括,就是:
(1)在不停掉老进程的情况下,启动新进程。
(2)老进程负责处理仍然没有处理完的请求,但不再接受处理请求。
(3)新进程接受新请求。
(4)老进程处理完所有请求,关闭所有连接后,停止。
这样就很方便地实现了平滑升级。一般有两种情况下需要升级 nginx,一种是确实要升级 nginx 的版本,另一种是要为 nginx 添加新的模块。

2、nginx 平滑升级原理

多进程模式下的请求分配方式
nginx 默认工作在多进程模式下,即主进程(master process)启动后完成配置加载和端口绑定等动作,fork出指定数量的工作进程(worker process),这些子进程会持有监听端口的文件描述符(fd),并通过在该描述符上添加监听事件来接受连接(accept)。

信号的接收和处理
nginx 主进程在启动完成后会进入等待状态,负责响应各类系统消息,如SIGCHLD、SIGHUP、SIGUSR2等。

Nginx信号简介

主进程支持的信号

  • TERM, INT: 立刻退出
  • QUIT: 等待工作进程结束后再退出
  • KILL: 强制终止进程
  • HUP: 重新加载配置文件,使用新的配置启动工作进程,并逐步关闭旧进程。
  • USR1: 重新打开日志文件
  • USR2: 启动新的主进程,实现热升级
  • WINCH: 逐步关闭工作进程

工作进程支持的信号

  • TERM, INT: 立刻退出
  • QUIT: 等待请求处理结束后再退出
  • USR1: 重新打开日志文件

3、nginx 平滑升级实战

1、查看现有的 nginx 编译参数

[root@web ~]#/usr/local/nginx/sbin/nginx -V

按照原来的编译参数安装 nginx 的方法进行安装,只需要到 make,千万不要 make install

2、编译新的 nginx 源码包

编译新Nginx源码,安装路径需与旧版一致 (详细过程可参见:Nginx编译安装与配置使用)

[root@web ~]#./configure --prefix=/usr/local/nginx-1.14.0 --user=www --group=www --with-http_ssl_module --with-openssl=/path/to/openssl_src
[root@web ~]#make

3、备份原 nginx 二进制文件

备份二进制文件和 nginx 的配置文件(期间nginx不会停止服务)

[root@web ~]#mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx_$(date +%F)

4、复制新的nginx二进制文件,进入新的nginx源码包

[root@web ~]#cp /usr/local/nginx-1.14.0/objs/nginx /usr/local/nginx/sbin/

5、测试新版本的nginx是否正常

[root@web ~]#/usr/local/nginx/sbin/nginx -t

6、给nginx发送平滑迁移信号(若不清楚pid路径,请查看nginx配置文件)

[root@web ~]#kill -USR2 cat /var/run/nginx.pid

7、查看nginx pid,会出现一个nginx.pid.oldbin

[root@web ~]#ll /var/run/nginx.pid*

8、从容关闭旧的Nginx进程

[root@web ~]#kill -WINCH cat /var/run/nginx.pid.oldbin

9、此时不重载配置启动旧的工作进程

[root@web ~]#kill -HUP cat /var/run/nginx.pid.oldbin

10、结束工作进程,完成此次升级

[root@web ~]#kill -QUIT cat /var/run/nginx.pid.oldbin

11、验证Nginx是否升级成功

[root@web ~]#usr/local/nginx/sbin/nginx -V

4、升级实验

1、安装配置1.6版本的 nginx

[root@web ~]# yum install -y gcc gcc-c++ pcre-devel openssl-devel zlib-devel
[root@web ~]# tar zxvf nginx-1.6.0.tar.gz -C /usr/src/
[root@web ~]# cd /usr/src/nginx-1.6.0/
[root@web nginx-1.6.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module
[root@web nginx-1.6.0]# make 
[root@web nginx-1.6.0]# make install
[root@web nginx-1.6.0]# ln -s /usr/local/nginx/sbin/* /usr/sbin/
[root@web nginx-1.6.0]# useradd -M -s /sbin/nologin nginx 
[root@web nginx-1.6.0]# nginx 
[root@web nginx-1.6.0]# netstat -anput | grep nginx 
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 19008/nginx: master

2、查看 nginx 版本

[root@web nginx-1.6.0]# nginx -v
nginx version: nginx/1.6.0

3、查看 nginx 现有安装的模块

[root@web nginx-1.6.0]# nginx -V
nginx version: nginx/1.6.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-11) (GCC) 
configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module

4、访问验证

[root@web nginx-1.6.0]# echo "nginx1.6.0" > /usr/local/nginx/html/index.html
[root@web nginx-1.6.0]# elinks 192.168.20.167

在这里插入图片描述

5、升级 nginx

将 nginx 版本进行升级 并在不影响业务的情况下添加 SSL 和 pcre 模块

[root@web ~]# tar zxvf nginx-1.11.2.tar.gz -C /usr/src/

[root@web ~]# cd /usr/src/nginx-1.11.2/
[root@web nginx-1.11.2]# ./configure --prefix=/usr/local/nginx --user=nginx --group=ngiinx --with-http_stub_status_module --with-http_ssl_module --with-pcre

[root@web nginx-1.11.2]# make

[root@web nginx-1.11.2]# cd
[root@web ~]# mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx_old 
[root@web ~]# cp /usr/src/nginx-1.11.2/objs/nginx /usr/local/nginx/sbin/

[root@web ~]# mv /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.old
[root@Centos ~]# cp /usr/src/nginx-1.11.2/conf/nginx.conf /usr/local/nginx/conf/nginx.conf

[root@web ~]# kill -USR2 `cat /usr/local/nginx/logs/nginx.pid`
[root@web ~]# ls /usr/local/nginx/logs/
access.log error.log nginx.pid

[root@web ~]# ps aux | grep nginx 
root 19008 0.0 0.0 24324 944 ? Ss 14:07 0:00 nginx: master process nginx
nginx 19009 0.0 0.1 26832 1744 ? S 14:07 0:00 nginx: worker process
root 53194 0.0 0.0 112660 976 pts/0 R+ 14:36 0:00 grep --color=auto ngin

6、验证 nginx 是否升级成功

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值