nginx学习使用
创始人
2024-03-04 22:38:23
0

nginx学习使用

  • 一、nginx安装与使用
    • 1、linux安装
    • 2、linux卸载
    • 3、升级
    • 4、linux环境下,把nginx设置为开启自启动
  • 二、nginx常用命令
    • 1、部署命令
    • 2、其他命令
  • 三、配置文件解析
    • 1、系统配置
    • 2、各配置指令详解
    • 3、日志配置
    • 4、跟据上面的命令,实现一个代理配置案例
    • 5、静态资源优化配置语法
    • 6、跨域配置
    • 7、Rewrite功能配置
    • 8、目录自动添加"/"
    • 9、合并目录
  • 四、Nginx静态资源压缩实战与缓存
    • 1、Gzip模块配置指令
    • 2、Gzip压缩功能的实例配置
    • 3、Gzip和sendfile共存问题
    • 4、gzip_static测试使用
    • 5、静态资源的缓存处理
    • 6、浏览器缓存相关指令
    • 7、静态资源防盗链
    • 8、spenssl生成证书
  • 五、nginx反向代理
    • 1、proxy_pass
    • 2、proxy_set_header
    • 3、proxy_redirect
    • 4、nginx反向代理实战
  • 六、负载均衡
    • 1、负载均衡的作用
    • 2、Nginx七层负载均衡
    • 3、Nginx七层负载均衡的指令
    • 4、负载均衡(轮询访问)案例
    • 5、负载均衡状态
    • 6、负载均衡策略
    • 7、负载均衡案例
  • 八、缓存集成
    • 1、Nginx缓存设置的相关指令
    • 2、Nginx缓存设置案例
    • 3、Nginx缓存的清除
    • 4、Nginx设置资源不缓存
  • 九、实战:Nginx实现服务器端集群搭建
  • 十、下面补充几个nginx的置nginx.conf模板

一、nginx安装与使用

1、linux安装

在这里插入图片描述

2、linux卸载

在这里插入图片描述

3、升级

在这里插入图片描述
在这里插入图片描述

4、linux环境下,把nginx设置为开启自启动

经过前面的操作,我们会发现,如果想要启动、关闭或重新加载nginx配置文件,都需要先进入到nginx的安装目录的sbin目录,然后使用nginx的二级制可执行文件来操作,相对来说操作比较繁琐,这块该如何优化?另外如果我们想把Nginx设置成随着服务器启动就自动完成启动操作,又该如何来实现?这就需要用到接下来我们要讲解的两个知识点

第一步,nginx配置成系统服务
(1) 在/usr/lib/systemd/system目录下添加nginx.service,内容如下:

vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx web service
Documentation=http://nginx.org/en/docs/
After=network.target[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true[Install]
WantedBy=default.target

(2)添加完成后如果权限有问题需要进行权限设置

chmod 755 /usr/lib/systemd/system/nginx.service

(3)使用系统命令来操作Nginx服务

启动: systemctl start nginx
停止: systemctl stop nginx
重启: systemctl restart nginx
重新加载配置文件: systemctl reload nginx
查看nginx状态: systemctl status nginx
开机启动: systemctl enable nginx

第二步,nginx命令配置到系统环境

(1)修改/etc/profile文件

vim /etc/profile
在最后一行添加
export PATH=$PATH:/usr/local/nginx/sbin

(2)使之立即生效

source /etc/profile

(3)执行nginx命令

nginx -V

二、nginx常用命令

1、部署命令

  • 查看 nginx进程 : ps -ef|grep nginx 或者 查看文件./logs/nginx.pid 里面有记录进程号

  • 查看某端口进程(不同linux系统使用的不同):netstat -tunlp |grep 8300netstat -ano|findstr 12001

  • liunx关闭nginx进程 : kill -9 进程号 或者 kill -TERM 进程号(直接关闭服务,不论当前是否有请求未处理完) 或者 kill -QUIT 进程号(不再接受新的请求,处理完已有请求后优雅的关闭服务),补充一点,如果不想单独去查询nginx的进程号,直接使用命令,可以用飘号``来执行命令脚本,将执行的结果作为动态参数,比如在这里插入图片描述

  • Linux重新加载配置文件(在不重启服务的情况下重新读取配置nginx.conf):kill -HUP 进程号
    其中各参数的详细描述如下图:
    在这里插入图片描述

  • 查看nginx的配置文件nginx.conf中是否有语法错误./nginx -t 或者使用./nginx -T它与-t的区别就是会将所有信息显示出来

  • 指定nginx配置文件启动,带上-c参数:./nginx -c /usr/local/abc.conf

  • 启动nginx时设置全局变量,带上参数-g./nginx -g "pid logs/abd.pid"

  • Windows关闭nginx:taskkill /f /t /im nginx.exe

  • Windows关闭nginx:taskkill /f /t /im nginx.exe

  • 开启nginx进程 : ./nginx

  • 停止nginx服务: (在nginx的 sbin目录下) ./nginx -s stop

  • 重启nginx服务:nginx -s reload

  • 假如我们要找一个nginx配置文件nginx.conf,那么我们可以通过find命令

  • 查找:find . -name ‘nginx.conf’

2、其他命令

1、给nginx添加扩展模块后重新编译

》将原有/usr/local/nginx/sbin/nginx进行备份
》拷贝nginx之前的配置信息,使用命令nginx -V来查看
》在nginx的安装源码进行配置指定对应模块  ./configure --with-http_ssl_module
》通过make模板进行编译
》将objs下面的nginx移动到/usr/local/nginx/sbin下
》在源码目录下执行  make upgrade进行升级,这个可以实现不停机添加新模块的功能

三、配置文件解析

1、系统配置

其他nginx配置的参考博客nginx配置说明
在这里插入图片描述
nginx配置详解

# 概述:一共三大部分配置。
# 其中#注释掉的可以在需要的时候开启并修改,没有注释掉的(除了下面location示例)不要删掉,基本都是必须的配置项。###############################第一部分 全局配置############################
#user  nobody;                        指定启动进程的用户,默认不用指定即可。
#error_log  logs/error.log;           配置日志输出,虽然叫error_log但是可以定义输出的级别,默认不写是ERROR级别,建议不要设置为info以下的级别,因为会带来大量的磁盘I/O消耗,影响nginx性能
#error_log  logs/error.log  notice;   
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;           记录pid的文件,默认就是放到这个位置,可以修改。# 只启动一个进程,nginx是多进程单线程模型,但是使用了epoll sendfile 非阻塞io
worker_processes  1;
#是否以守护进程方式启动,默认是打开的(on)如果关闭(off),则ctrl+c后就自动关闭了
#daemon off;
#引用别的外部配置文件
#include myNginx.conf
###############################第二部分 event配置############################
#主要是网络连接相关的配置
events {# 每个worker能连接1024个链接worker_connections  1024;#use epoll; 事件驱动模型select|poll|kqueue|epoll|resig
}###############################第三部分 http配置############################
http {include       mime.types;  #文件扩展名与文件类型映射表default_type  text/html;   #默认的返回类型,可以在server.location里面改sendfile        on;        #开启sendfile系统调用keepalive_timeout  65;     #连接超时时间65sserver {listen       80;# 下面展示多个demo,demo之间互相没有依赖关系,可以单独配置来进行测试。# 其中demo1到demo6 是nginx相关的。#返回一个字符串location /get_text {return 200 

This is a nginx text

;}############### demo1 展示location路径的不同写法优先级 ################ =最高优先级 表示路径完全等于,可以匹配/demo1/a/b的请求location =/demo1/a/b {echo "=/demo1/a/b";} # ^~第二高 表示startsWith,可以匹配/demo1/a/b/c和/demo1/abc请求location ^~/demo1/a {echo "^~/demo1/a";}# ~等四个符号第三高 表示正则,如果要用{}是特殊符号,需要整个加引号,建议直接加双引号,防止出错,可以匹配/demo1/bcd# 其他三个:~*不区分大小写正则,!~正则不匹配的,!~*不分大小写的正则不匹配location "~/demo1/\w{3}$" {echo "regex";}# 最低 没有前置符号 /demo1 /demo111 /demo1/b/c 不符合上面三种,就会匹配到这location /demo1{echo "/demo1";}############### demo2 展示serve静态文件夹 ###############location / {root html; # root就是根目录是当前html目录index index.html index.htm; # index表示默认不写的时候转到的文件}############## demo3 指定错误文件 ###############error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}############# demo4 rewrite重写url rewrite也可以是server级别 ####################location /demo4 {# 一般放到最后一行rewrite ^/(.*) /$1/api permanent; # permanent301, redirect302, break不在匹配后面rewrite规则,last继续向下匹配。}location /demo4/api {echo "/demo4/api";}############# demo5 demo6 proxy_pass反向代理 ##################### /demo5 => baidu.com/demo5# /demo5/a/b => baidu.com/demo5/a/blocation /demo5 {proxy_pass https://www.baidu.com;}# /demo6 => baidu.com# /demo6/a/b => baidu.com/a/blocation /demo6 {# proxy_set_header Host $http_host; 如果有请求头改动的需求可以搜索proxy_set_header去了解proxy_pass https://www.baidu.com/;}}# 下面demo7到demo11是openresty lua的一些配置demoserver {listen 81;############# demo7 init_by_lua_block 用来加载经常用到的库 或者 用来对多进程shared变量赋值 ####################init_by_lua_block {cjson = require("cjson") --后续的lua流程中可以直接使用cjsonlocal myname = ngx.shared.info --可以认为是静态变量,通过info:get获取变量值info:set("name", "frank")info:set("age", 77)}############# demo8 demo9 rewrite_by_lua_block 配合ngx.redirect用来替换rewrite指令 ##################### 注意rewrite_by_lua和因为作用阶段是nginx原生rewrite之后,所以容易和原生一起用的时候出错,最好的方式就是只用lua的不要用nginx的了。location /demo8 {set $a 1;set $b "";rewrite_by_lua_block {ngx.var.b = tonumber(ngx.var.a) + 1if tonumber(ngx.var.b) == 2 thenreturn ngx.redirect("/demo9") --默认是302,如果要301或307可以再加一个第二参数即可end}echo "demo8"; # 注意echo是content阶段的,rewrite阶段重定向了请求,就走不到这里了}location /demo9 {echo "demo9";}############# demo10 access_by_lua_block 用来做一些加载内容前的准备工作例如访问redis看看用户身份是不是合法 ip是不是合法等 ####################location /demo10 {access_by_lua_block {local res = ngx.location.capture("/auth") -- ngx.location.capture是作为客户端发起http请求拿到结果if res.status == ngx.HTTP_OK thenreturn -- 正常return就能走到content阶段endif res.status == ngx.HTTP_FORBIDDEN thenngx.exit(res.status) -- exit + 状态码 就直接返回状态码了endngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)}echo "demo10"; # 如果合法的话就返回demo10字样}location /auth {return 200; # 换成403 or 500试试}############# demo10 content_by_lua_block 用来作为content阶段的脚本,一般测试用的多 #####################不要和 echo proxy_pass等content阶段指令一起用location /demo10 {content_by_lua_block{ngx.say("/demo10");ngx.say("/demo11"); -- 和外部用俩echo效果类似。ngx.say ngx.print区别是前者会多个回车在最后}# echo "echo10"; 如果外面用了echo,则只有echo的效果# proxy_pass http://www.baidu.com; 如果外面用了proxy_pass也是只有proxy_pass效果了,因为都是content阶段,content只能一个生效。}############# demo11 rewrite_by_lua与proxy_pass配合 根据参数进行转发 ####################location /demo11 {default_type text/html;set $proxy "";rewrite_by_lua ' # 千万别用content,因为content和proxy_pass阶段犯冲local h = ngx.var.host # 这里从host中提出第一个.之前的部分看是不是a来决定转发到哪local dot = h:find("%.")local prefix = h:sub(1,dot-1)if prefix == "a" thenngx.var.proxy="127.0.0.1:3000"elsengx.var.proxy="127.0.0.1:5500"end';proxy_pass http://$proxy$uri;}} }

2、各配置指令详解

(1)
在这里插入图片描述
(2)
在这里插入图片描述
(3)
在这里插入图片描述
(4)响应类型配置 default_type
在这里插入图片描述
(5)server_name:用来设置虚拟主机服务名称。

127.0.0.1 、 localhost 、域名[www.baidu.com | www.jd.com]

语法server_name name …;
name可以提供多个中间用空格分隔
默认值server_name “”;
位置server

关于server_name的配置方式有三种,分别是:

精确匹配
通配符匹配
正则表达式匹配

配置方式一:精确匹配

如:

server {listen 80;server_name www.itcast.cn www.itheima.cn;...
}

配置方式二:使用通配符配置

server_name中支持通配符"*",但需要注意的是通配符不能出现在域名的中间,只能出现在首段或尾段,如:

server {listen 80;server_name  *.itcast.cn	www.itheima.*;# www.itcast.cn abc.itcast.cn www.itheima.cn www.itheima.com...
}

下面的配置就会报错

server {listen 80;server_name  www.*.cn www.itheima.c*...
}

配置三:使用正则表达式配置

server_name中可以使用正则表达式,并且使用~作为正则表达式字符串的开始标记。

常见的正则表达式

代码说明
^匹配搜索字符串开始位置
$匹配搜索字符串结束位置
.匹配除换行符\n之外的任何单个字符
\转义字符,将下一个字符标记为特殊字符
[xyz]字符集,与任意一个指定字符匹配
[a-z]字符范围,匹配指定范围内的任何字符
\w与以下任意字符匹配 A-Z a-z 0-9 和下划线,等效于[A-Za-z0-9_]
\d数字字符匹配,等效于[0-9]
{n}正好匹配n次
{n,}至少匹配n次
{n,m}匹配至少n次至多m次
*零次或多次,等效于{0,}
+一次或多次,等效于{1,}
?零次或一次,等效于{0,1}

配置如下:

server{listen 80;server_name ~^www\.(\w+)\.com$;default_type text/plain;return 200 $1  $2 ..;
}
注意 ~后面不能加空格,括号可以取值

匹配执行顺序,和上面的location优先级基本一致

由于server_name指令支持通配符和正则表达式,因此在包含多个虚拟主机的配置文件中,可能会出现一个名称被多个虚拟主机的server_name匹配成功,当遇到这种情况,当前的请求交给谁来处理呢?

server{listen 80;server_name ~^www\.\w+\.com$;default_type text/plain;return 200 'regex_success';
}server{listen 80;server_name www.itheima.*;default_type text/plain;return 200 'wildcard_after_success';
}server{listen 80;server_name *.itheima.com;default_type text/plain;return 200 'wildcard_before_success';
}server{listen 80;server_name www.itheima.com;default_type text/plain;return 200 'exact_success';
}server{listen 80 default_server;server_name _;default_type text/plain;return 444 'default_server not found server';
}

结论:

exact_success
wildcard_before_success
wildcard_after_success
regex_success
default_server not found server!!
No1:准确匹配server_nameNo2:通配符在开始时匹配server_name成功No3:通配符在结束时匹配server_name成功No4:正则表达式匹配server_name成功No5:被默认的default_server处理,如果没有指定默认找第一个server

(6)、default_server属性是标识符,用来将此虚拟主机设置成默认主机。所谓的默认主机指的是如果没有匹配到对应的address:port,则会默认执行的。如果不指定默认使用的是第一个server。

server{listen 8080;server_name 127.0.0.1;location /{root html;index index.html;}
}
server{listen 8080 default_server;server_name localhost;default_type text/plain;return 444 'This is a error request';
}

(6)、location指令

server{listen 80;server_name localhost;location / {}location /abc{}...
}

location:用来设置请求的URI

语法location [ = | ~ | ~* | ^~ |@ ] uri{…}
默认值
位置server,location

uri变量是待匹配的请求字符串,可以不包含正则表达式,也可以包含正则表达式,那么nginx服务器在搜索匹配location的时候,是先使用不包含正则表达式进行匹配,找到一个匹配度最高的一个,然后在通过包含正则表达式的进行匹配,如果能匹配到直接访问,匹配不到,就使用刚才匹配度最高的那个location来处理请求。

属性介绍:

不带符号,要求必须以指定模式开始

server {listen 80;server_name 127.0.0.1;location /abc{default_type text/plain;return 200 "access success";}
}
以下访问都是正确的
http://192.168.200.133/abc
http://192.168.200.133/abc?p1=TOM
http://192.168.200.133/abc/
http://192.168.200.133/abcdef

= : 用于不包含正则表达式的uri前,必须与指定的模式精确匹配

server {listen 80;server_name 127.0.0.1;location =/abc{default_type text/plain;return 200 "access success";}
}
可以匹配到
http://192.168.200.133/abc
http://192.168.200.133/abc?p1=TOM
匹配不到
http://192.168.200.133/abc/
http://192.168.200.133/abcdef

~ : 用于表示当前uri中包含了正则表达式,并且区分大小写
~*: 用于表示当前uri中包含了正则表达式,并且不区分大小写

换句话说,如果uri包含了正则表达式,需要用上述两个符合来标识

server {listen 80;server_name 127.0.0.1;location ~^/abc\w${default_type text/plain;return 200 "access success";}
}
server {listen 80;server_name 127.0.0.1;location ~*^/abc\w${default_type text/plain;return 200 "access success";}
}

^~: 用于不包含正则表达式的uri前,功能和不加符号的一致,唯一不同的是,如果模式匹配,那么就停止搜索其他模式了。

server {listen 80;server_name 127.0.0.1;location ^~/abc{default_type text/plain;return 200 "access success";}
}

(7)、设置请求资源的目录root / alias
root:设置请求的根目录

语法root path;
默认值root html;
位置http、server、location

path为Nginx服务器接收到请求以后查找资源的根目录路径。

alias:用来更改location的URI

语法alias path;
默认值
位置location

path为修改后的根路径。

以上两个指令都可以来指定访问资源的路径,那么这两者之间的区别是什么?

举例说明:

(1)在/usr/local/nginx/html目录下创建一个 images目录,并在目录下放入一张图片mv.png图片

location /images {root /usr/local/nginx/html;
}

访问图片的路径为:

http://192.168.200.133/images/mv.png

(2)如果把root改为alias

location /images {alias /usr/local/nginx/html;
}

再次访问上述地址,页面会出现404的错误,查看错误日志会发现是因为地址不对,所以验证了:

root的处理结果是: root路径+location路径
/usr/local/nginx/html/images/mv.png
alias的处理结果是:使用alias路径替换location路径
/usr/local/nginx/html/images

需要在alias后面路径改为

location /images {alias /usr/local/nginx/html/images;
}

(3)如果location路径是以/结尾,则alias也必须是以/结尾,root没有要求

将上述配置修改为

location /images/ {alias /usr/local/nginx/html/images;
}

访问就会出问题,查看错误日志还是路径不对,所以需要把alias后面加上 /

小结:

root的处理结果是: root路径+location路径
alias的处理结果是:使用alias路径替换location路径
alias是一个目录别名的定义,root则是最上层目录的含义。
如果location路径是以/结尾,则alias也必须是以/结尾,root没有要求

(8)、index指令
index:设置网站的默认首页

语法index file …;
默认值index index.html;
位置http、server、location

index后面可以跟多个设置,如果访问的时候没有指定具体访问的资源,则会依次进行查找,找到第一个为止。

举例说明:

location / {root /usr/local/nginx/html;index index.html index.htm;
}
访问该location的时候,可以通过 http://ip:port/,地址后面如果不添加任何内容,则默认依次访问index.html和index.htm,找到第一个来进行返回

(9)、error_page指令
error_page:设置网站的错误页面

语法error_page code … [=[response]] uri;
默认值
位置http、server、location…

当出现对应的响应code后,如何来处理。

举例说明:

(1)可以指定具体跳转的地址

server {error_page 404 http://www.itcast.cn;
}

(2)可以指定重定向地址

server{error_page 404 /50x.html;error_page 500 502 503 504 /50x.html;location =/50x.html{root html;}
}

(3)使用location的@符合完成错误信息展示

server{error_page 404 @jump_to_error;location @jump_to_error {default_type text/plain;return 404 'Not Found Page...';}
}

可选项=[response]的作用是用来将相应代码更改为另外一个

server{error_page 404 =200 /50x.html;location =/50x.html{root html;}
}
这样的话,当返回404找不到对应的资源的时候,在浏览器上可以看到,最终返回的状态码是200,这块需要注意下,编写error_page后面的内容,404后面需要加空格,200前面不能加空格

3、日志配置

在这里插入图片描述
日志自定义格式用法,比如加入一些自定义字符串,如下图:(也可以配合一些内置变量使用)
在这里插入图片描述
结果如下
在这里插入图片描述
3、其他配置
在这里插入图片描述

4、跟据上面的命令,实现一个代理配置案例

Nginx服务器基础配置实例

前面我们已经对Nginx服务器默认配置文件的结构和涉及的基本指令做了详细的阐述。通过这些指令的合理配置,我们就可以让一台Nginx服务器正常工作,并且提供基本的web服务器功能。

接下来我们将通过一个比较完整和最简单的基础配置实例,来巩固下前面所学习的指令及其配置。

需求如下:

(1)有如下访问:http://192.168.200.133:8081/server1/location1访问的是:index_sr1_location1.htmlhttp://192.168.200.133:8081/server1/location2访问的是:index_sr1_location2.htmlhttp://192.168.200.133:8082/server2/location1访问的是:index_sr2_location1.htmlhttp://192.168.200.133:8082/server2/location2访问的是:index_sr2_location2.html
(2)如果访问的资源不存在,返回自定义的404页面
(3)将/server1和/server2的配置使用不同的配置文件分割将文件放到/home/www/conf.d目录下,然后使用include进行合并
(4)为/server1和/server2各自创建一个访问日志文件

配置的内容如下:


##全局块 begin##
#配置允许运行Nginx工作进程的用户和用户组
user www;
#配置运行Nginx进程生成的worker进程数
worker_processes 2;
#配置Nginx服务器运行对错误日志存放的路径
error_log logs/error.log;
#配置Nginx服务器允许时记录Nginx的master进程的PID文件路径和名称
pid logs/nginx.pid;
#配置Nginx服务是否以守护进程方法启动
#daemon on;
##全局块 end####events块 begin##
events{#设置Nginx网络连接序列化accept_mutex on;#设置Nginx的worker进程是否可以同时接收多个请求multi_accept on;#设置Nginx的worker进程最大的连接数worker_connections 1024;#设置Nginx使用的事件驱动模型use epoll;
}
##events块 end##
##http块 start##
http{#定义MIME-Typeinclude mime.types;default_type application/octet-stream;#配置允许使用sendfile方式运输sendfile on;#配置连接超时时间keepalive_timeout 65;#配置请求处理日志格式log_format server1 '===>server1 access log';log_format server2 '===>server2 access log';##server块 开始##include /home/www/conf.d/*.conf;##server块 结束##
}
##http块 end##

server1.conf

server{#配置监听端口和主机名称listen 8081;server_name localhost;#配置请求处理日志存放路径access_log /home/www/myweb/server1/logs/access.log server1;#配置错误页面error_page 404 /404.html;#配置处理/server1/location1请求的locationlocation /server1/location1{root /home/www/myweb;index index_sr1_location1.html;}#配置处理/server1/location2请求的locationlocation /server1/location2{root /home/www/myweb;index index_sr1_location2.html;}#配置错误页面转向location = /404.html {root /home/www/myweb;index 404.html;}
}

server2.conf

server{#配置监听端口和主机名称listen 8082;server_name localhost;#配置请求处理日志存放路径access_log /home/www/myweb/server2/logs/access.log server2;#配置错误页面,对404.html做了定向配置error_page 404 /404.html;#配置处理/server1/location1请求的locationlocation /server2/location1{root /home/www/myweb;index index_sr2_location1.html;}#配置处理/server2/location2请求的locationlocation /server2/location2{root /home/www/myweb;index index_sr2_location2.html;}#配置错误页面转向location = /404.html {root /home/www/myweb;index 404.html;}}

5、静态资源优化配置语法

Nginx对静态资源如何进行优化配置。这里从三个属性配置进行优化:

sendfile on;
tcp_nopush on;
tcp_nodeplay on;

(1)sendfile,用来开启高效的文件传输模式。

语法sendfile on |off;
默认值sendfile off;
位置http、server、location…

请求静态资源的过程:客户端通过网络接口向服务端发送请求,操作系统将这些客户端的请求传递给服务器端应用程序,服务器端应用程序会处理这些请求,请求处理完成以后,操作系统还需要将处理得到的结果通过网络适配器传递回去。

如:

server {listen 80;server_name localhost;location / {root html;index index.html;}
}
在html目录下有一个welcome.html页面,访问地址
http://192.168.200.133/welcome.html

(2)tcp_nopush:该指令必须在sendfile打开的状态下才会生效,主要是用来提升网络包的传输’效率’

语法tcp_nopush on|off;
默认值tcp_nopush off;
位置http、server、location

(3)tcp_nodelay:该指令必须在keep-alive连接开启的情况下才生效,来提高网络包传输的’实时性’

语法tcp_nodelay on|off;
默认值tcp_nodelay on;
位置http、server、location

经过刚才的分析,“tcp_nopush"和”tcp_nodelay“看起来是"互斥的”,那么为什么要将这两个值都打开,这个大家需要知道的是在linux2.5.9以后的版本中两者是可以兼容的,三个指令都开启的好处是,sendfile可以开启高效的文件传输模式,tcp_nopush开启可以确保在发送到客户端之前数据包已经充分“填满”, 这大大减少了网络开销,并加快了文件发送的速度。 然后,当它到达最后一个可能因为没有“填满”而暂停的数据包时,Nginx会忽略tcp_nopush参数, 然后,tcp_nodelay强制套接字发送数据。由此可知,TCP_NOPUSH可以与TCP_NODELAY一起设置,它比单独配置TCP_NODELAY具有更强的性能。所以我们可以使用如下配置来优化Nginx静态资源的处理

sendfile on;
tcp_nopush on;
tcp_nodelay on;

6、跨域配置

浏览器的同源策略:是一种约定,是浏览器最核心也是最基本的安全功能,如果浏览器少了同源策略,则浏览器的正常功能可能都会受到影响。

同源: 协议、域名(IP)、端口相同即为同源

出现跨域问题会有什么效果?,接下来通过一个需求来给大家演示下:

(1)nginx的html目录下新建一个a.html

跨域问题演示

(2)在nginx.conf配置如下内容

server{listen  8080;server_name localhost;location /getUser{default_type application/json;return 200 '{"id":1,"name":"TOM","age":18}';}
}
server{listen 	80;server_name localhost;location /{root html;index index.html;}
}

解决方案

使用add_header指令,该指令可以用来添加一些头信息

语法add_header name value…
默认值
位置http、server、location

此处用来解决跨域问题,需要添加两个头信息,一个是Access-Control-Allow-Origin,Access-Control-Allow-Methods

Access-Control-Allow-Origin: 直译过来是允许跨域访问的源地址信息,可以配置多个(多个用逗号分隔),也可以使用*代表所有源

Access-Control-Allow-Methods:直译过来是允许跨域访问的请求方式,值可以为 GET POST PUT DELETE…,可以全部设置,也可以根据需要设置,多个用逗号分隔

具体配置方式

location /getUser{add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;default_type application/json;return 200 '{"id":1,"name":"TOM","age":18}';
}

7、Rewrite功能配置

Rewrite是Nginx服务器提供的一个重要基本功能,是Web服务器产品中几乎必备的功能。主要的作用是用来实现URL的重写。

注意:Nginx服务器的Rewrite功能的实现依赖于PCRE的支持,因此在编译安装Nginx服务器之前,需要安装PCRE库。Nginx使用的是ngx_http_rewrite_module模块来解析和处理Rewrite功能的相关配置。

(1)、“地址重写"与"地址转发”
重写和转发的区别:

地址重写浏览器地址会发生变化而地址转发则不变
一次地址重写会产生两次请求而一次地址转发只会产生一次请求
地址重写到的页面必须是一个完整的路径而地址转发则不需要
地址重写因为是两次请求所以request范围内属性不能传递给新页面而地址转发因为是一次请求所以可以传递值
地址转发速度快于地址重写

(2)、Rewrite规则
(2-1)、set指令
该指令用来设置一个新的变量。

语法set $variable value;
默认值
位置server、location、if

variable:变量的名称,该变量名称要用"$"作为变量的第一个字符,且不能与Nginx服务器预设的全局变量同名。

value:变量的值,可以是字符串、其他变量或者变量的组合等。
比如:
在这里插入图片描述

(2-2)、 Rewrite常用全局变量

变量说明
$args变量中存放了请求URL中的请求指令。比如http://192.168.200.133:8080?arg1=value1&args2=value2中的"arg1=value1&arg2=value2",功能和$query_string一样
$http_user_agent变量存储的是用户访问服务的代理信息(如果通过浏览器访问,记录的是浏览器的相关版本信息)
$host变量存储的是访问服务器的server_name值
$document_uri变量存储的是当前访问地址的URI。比如http://192.168.200.133/server?id=10&name=zhangsan中的"/server",功能和$uri一样
$document_root变量存储的是当前请求对应location的root值,如果未设置,默认指向Nginx自带html目录所在位置
$content_length变量存储的是请求头中的Content-Length的值
$content_type变量存储的是请求头中的Content-Type的值
$http_cookie变量存储的是客户端的cookie信息,可以通过add_header Set-Cookie 'cookieName=cookieValue’来添加cookie数据
$limit_rate变量中存储的是Nginx服务器对网络连接速率的限制,也就是Nginx配置中对limit_rate指令设置的值,默认是0,不限制。
$remote_addr变量中存储的是客户端的IP地址
$remote_port变量中存储了客户端与服务端建立连接的端口号
$remote_user变量中存储了客户端的用户名,需要有认证模块才能获取
$scheme变量中存储了访问协议
$server_addr变量中存储了服务端的地址
$server_name变量中存储了客户端请求到达的服务器的名称
$server_port变量中存储了客户端请求到达服务器的端口号
$server_protocol变量中存储了客户端请求协议的版本,比如"HTTP/1.1"
$request_body_file变量中存储了发给后端服务器的本地文件资源的名称
$request_method变量中存储了客户端的请求方式,比如"GET","POST"等
$request_filename变量中存储了当前请求的资源文件的路径名
$request_uri变量中存储了当前请求的URI,并且携带请求参数,比如http://192.168.200.133/server?id=10&name=zhangsan中的"/server?id=10&name=zhangsan"

(2-3)、if指令

该指令用来支持条件判断,并根据条件判断结果选择不同的Nginx配置。

语法if (condition){…}
默认值
位置server、location

condition为判定条件,可以支持以下写法:(注意,if中间一定要有一个空格)

  1. 变量名。如果变量名对应的值为空或者是0,if都判断为false,其他条件为true。
if ($param){}
2. 使用"="和"!="比较变量和字符串是否相等,满足条件为true,不满足为false
if ($request_method = POST){return 405;
}

注意:此处和Java不太一样的地方是字符串不需要添加引号。

  1. 使用正则表达式对变量进行匹配,匹配成功返回true,否则返回false。变量与正则表达式之间使用"~","~*","!~","!~\*"来连接。

    "~"代表匹配正则表达式过程中区分大小写,

    "~*"代表匹配正则表达式过程中不区分大小写

    "!~“和”!~*"刚好和上面取相反值,如果匹配上返回false,匹配不上返回true

if ($http_user_agent ~ MSIE){#$http_user_agent的值中是否包含MSIE字符串,如果包含返回true
}

注意:正则表达式字符串一般不需要加引号,但是如果字符串中包含"}“或者是”;"等字符时,就需要把引号加上。

  1. 判断请求的文件是否存在使用"-f"和"!-f",

    当使用"-f"时,如果请求的文件存在返回true,不存在返回false。

    当使用"!f"时,如果请求文件不存在,但该文件所在目录存在返回true,文件和目录都不存在返回false,如果文件存在返回false

if (-f $request_filename){#判断请求的文件是否存在
}
if (!-f $request_filename){#判断请求的文件是否不存在
}
  1. 判断请求的目录是否存在使用"-d"和"!-d",

    当使用"-d"时,如果请求的目录存在,if返回true,如果目录不存在则返回false

    当使用"!-d"时,如果请求的目录不存在但该目录的上级目录存在则返回true,该目录和它上级目录都不存在则返回false,如果请求目录存在也返回false.

  2. 判断请求的目录或者文件是否存在使用"-e"和"!-e"

    当使用"-e",如果请求的目录或者文件存在时,if返回true,否则返回false.

    当使用"!-e",如果请求的文件和文件所在路径上的目录都不存在返回true,否则返回false

  3. 判断请求的文件是否可执行使用"-x"和"!-x"

    当使用"-x",如果请求的文件可执行,if返回true,否则返回false

    当使用"!-x",如果请求文件不可执行,返回true,否则返回false

(2-4)、break指令

该指令用于中断当前相同作用域中的其他Nginx配置。与该指令处于同一作用域的Nginx配置中,位于它前面的指令配置生效,位于后面的指令配置无效。

语法break;
默认值
位置server、location、if

例子:
一个break;的作用域为一个{}

location /{if ($param){set $id $1;break;limit_rate 10k;}
}

(2-5)、return指令
该指令用于完成对请求的处理,直接向客户端返回响应状态代码。在return后的所有Nginx配置都是无效的。

语法return code [text];
return code URL;
return URL;
默认值
位置server、location、if

code:为返回给客户端的HTTP状态代理。可以返回的状态代码为0~999的任意HTTP状态代理

text:为返回给客户端的响应体内容,支持变量的使用

URL:为返回给客户端的URL地址

(2-6)、rewrite指令

该指令通过正则表达式的使用来改变URI。可以同时存在一个或者多个指令,按照顺序依次对URL进行匹配和处理。

URL和URI的区别:

URI:统一资源标识符
URL:统一资源定位符
语法rewrite regex replacement [flag];
默认值
位置server、location、if

regex:用来匹配URI的正则表达式

replacement:匹配成功后,用于替换URI中被截取内容的字符串。如果该字符串是以"http://"或者"https://"开头的,则不会继续向下对URI进行其他处理,而是直接返回重写后的URI给客户端。

location rewrite {rewrite ^/rewrite/url\w*$ https://www.baidu.com;rewrite ^/rewrite/(test)\w*$ /$1;rewrite ^/rewrite/(demo)\w*$ /$1;
}
location /test{default_type text/plain;return 200 test_success;
}
location /demo{default_type text/plain;return 200 demo_success;
}

flag:用来设置rewrite对URI的处理行为,可选值有如下:

  • last:终止继续在本location块中处理接收到的URI,并将此处重写的URI作为一个新的URI,使用各location块进行处理。该标志将重写后的URI重写在server块中执行,为重写后的URI提供了转入到其他location块的机会。
location rewrite {rewrite ^/rewrite/(test)\w*$ /$1 last;rewrite ^/rewrite/(demo)\w*$ /$1 last;
}
location /test{default_type text/plain;return 200 test_success;
}
location /demo{default_type text/plain;return 200 demo_success;
}

访问 http://192.168.200.133:8081/rewrite/testabc,能正确访问

  • break:将此处重写的URI作为一个新的URI,在本块中继续进行处理。该标志将重写后的地址在当前的location块中执行,不会将新的URI转向其他的location块。
location rewrite {#/test   /usr/local/nginx/html/test/index.htmlrewrite ^/rewrite/(test)\w*$ /$1 break;rewrite ^/rewrite/(demo)\w*$ /$1 break;
}
location /test{default_type text/plain;return 200 test_success;
}
location /demo{default_type text/plain;return 200 demo_success;
}

访问 http://192.168.200.133:8081/rewrite/demoabc,页面报404错误

  • redirect:将重写后的URI返回给客户端,状态码为302,指明是临时重定向URI,主要用在replacement变量不是以"http://"或者"https://"开头的情况。
location rewrite {rewrite ^/rewrite/(test)\w*$ /$1 redirect;rewrite ^/rewrite/(demo)\w*$ /$1 redirect;
}
location /test{default_type text/plain;return 200 test_success;
}
location /demo{default_type text/plain;return 200 demo_success;
}

访问http://192.168.200.133:8081/rewrite/testabc请求会被临时重定向,浏览器地址也会发生改变

  • permanent:将重写后的URI返回给客户端,状态码为301,指明是永久重定向URI,主要用在replacement变量不是以"http://"或者"https://"开头的情况。
location rewrite {rewrite ^/rewrite/(test)\w*$ /$1 permanent;rewrite ^/rewrite/(demo)\w*$ /$1 permanent;
}
location /test{default_type text/plain;return 200 test_success;
}
location /demo{default_type text/plain;return 200 demo_success;
}

访问http://192.168.200.133:8081/rewrite/testabc请求会被永久重定向,浏览器地址也会发生改变
(2-7)、rewrite_log指令

该指令配置是否开启URL重写日志的输出功能。

语法rewrite_log on|off;
默认值rewrite_log off;
位置http、server、location、if

开启后,URL重写的相关日志将以notice级别输出到error_log指令配置的日志文件汇总。
配置如下:

rewrite_log on;
error_log  logs/error.log notice;

(3)、Rewrite的案例
场景:先来看一个效果,如果我们想访问京东网站,大家都知道我们可以输入www.jd.com,但是同样的我们也可以输入www.360buy.com同样也都能访问到京东网站。这个其实是因为京东刚开始的时候域名就是www.360buy.com,后面由于各种原因把自己的域名换成了www.jd.com, 虽然说域名变量,但是对于以前只记住了www.360buy.com的用户来说,我们如何把这部分用户也迁移到我们新域名的访问上来,针对于这个问题,我们就可以使用Nginx中Rewrite的域名跳转来解决。

  • 通过Nginx实现访问www.itcast.cn
server {listen 80;server_name www.itcast.cn;location /{default_type text/html;return 200 '

welcome to itcast

';} }

通过Rewrite完成将www.ithema.com和www.itheima.cn的请求跳转到www.itcast.com

server {listen 80;server_name www.itheima.com www.itheima.cn;rewrite ^/ http://www.itcast.cn;
}

问题描述:如何在域名跳转的过程中携带请求的URI?

修改配置信息

server {listen 80;server_name www.itheima.com www.itheima.cn;rewrite ^(.*) http://www.itcast.cn$1;
}

(4)、域名镜像

镜像网站指定是将一个完全相同的网站分别放置到几台服务器上,并分别使用独立的URL进行访问。其中一台服务器上的网站叫主站,其他的为镜像网站。镜像网站和主站没有太大的区别,可以把镜像网站理解为主站的一个备份节点。可以通过镜像网站提供网站在不同地区的响应速度。镜像网站可以平衡网站的流量负载、可以解决网络宽带限制、封锁等。

而我们所说的域名镜像和网站镜像比较类似,上述案例中,将www.itheima.com和 www.itheima.cn都能跳转到www.itcast.cn,那么www.itcast.cn我们就可以把它起名叫主域名,其他两个就是我们所说的镜像域名,当然如果我们不想把整个网站做镜像,只想为其中某一个子目录下的资源做镜像,我们可以在location块中配置rewrite功能,比如:

server {listen          80;server_name     www.itheima.cn www.itheima.com;location /user {rewrite ^/user(.*)$ http://www.itcast.cn$1;}location /emp{default_type text/html;return 200 '

emp_success

';} }

8、目录自动添加"/"

通过一个例子来演示下问题:

server {listen	8082;server_name localhost;location /heima {root html;index index.html;}
}

通过http://192.168.200.133:8082/heima和通过http://192.168.200.133:8082/heima/访问的区别?

如果不加斜杠,Nginx服务器内部会自动做一个301的重定向,重定向的地址会有一个指令叫server_name_in_redirect on|off;来决定重定向的地址:

如果该指令为on重定向的地址为:  http://server_name:8082/目录名/;http://localhost:8082/heima/
如果该指令为off重定向的地址为:  http://原URL中的域名:8082/目录名/;http://192.168.200.133:8082/heima/

所以就拿刚才的地址来说,http://192.168.200.133:8082/heima如果不加斜杠,那么按照上述规则,如果指令server_name_in_redirect为on,则301重定向地址变为 http://localhost:8082/heima/,如果为off,则301重定向地址变为http://192.168.200.133:8082/heima/。后面这个是正常的,前面地址就有问题。

注意server_name_in_redirect指令在Nginx的0.8.48版本之前默认都是on,之后改成了off,所以现在我们这个版本不需要考虑这个问题,但是如果是0.8.48以前的版本并且server_name_in_redirect设置为on,我们如何通过rewrite来解决这个问题?

解决方案

我们可以使用rewrite功能为末尾没有斜杠的URL自动添加一个斜杠

server {listen	80;server_name localhost;server_name_in_redirect on;location /heima {if (-d $request_filename){rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;}}
}

9、合并目录

搜索引擎优化(SEO)是一种利用搜索引擎的搜索规则来提高目的网站在有关搜索引擎内排名的方式。我们在创建自己的站点时,可以通过很多中方式来有效的提供搜索引擎优化的程度。其中有一项就包含URL的目录层级一般不要超过三层,否则的话不利于搜索引擎的搜索也给客户端的输入带来了负担,但是将所有的文件放在一个目录下又会导致文件资源管理混乱并且访问文件的速度也会随着文件增多而慢下来,这两个问题是相互矛盾的,那么使用rewrite如何解决上述问题?

举例,网站中有一个资源文件的访问路径时 /server/11/22/33/44/20.html,也就是说20.html存在于第5级目录下,如果想要访问该资源文件,客户端的URL地址就要写成 http://192.168.200.133/server/11/22/33/44/20.html,

server {listen 8083;server_name localhost;location /server{root html;}
}

但是这个是非常不利于SEO搜索引擎优化的,同时客户端也不好记.使用rewrite我们可以进行如下配置:

server {listen 8083;server_name localhost;location /server{rewrite ^/server-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /server/$1/$2/$3/$4/$5.html last;}
}

这样的话,客户端只需要输入http://www.web.name/server-11-22-33-44-20.html就可以访问到20.html页面了。这里也充分利用了rewrite指令支持正则表达式的特性。

四、Nginx静态资源压缩实战与缓存

经过上述内容的优化,我们再次思考一个问题,假如在满足上述优化的前提下,我们传送一个1M的数据和一个10M的数据那个效率高?,答案显而易见,传输内容小,速度就会快。那么问题又来了,同样的内容,如果把大小降下来,我们脑袋里面要蹦出一个词就是"压缩",接下来,我们来学习Nginx的静态资源压缩模块。

在Nginx的配置文件中可以通过配置gzip来对静态资源进行压缩,相关的指令可以配置在http块、server块和location块中,Nginx可以通过

ngx_http_gzip_module模块
ngx_http_gzip_static_module模块
ngx_http_gunzip_module模块

对这些指令进行解析和处理。

接下来我们从以下内容进行学习

(1)Gzip各模块支持的配置指令
(2)Gzip压缩功能的配置
(3)Gzip和sendfile的冲突解决
(4)浏览器不支持Gzip的解决方案

1、Gzip模块配置指令

接下来所学习的指令都来自ngx_http_gzip_module模块,该模块会在nginx安装的时候内置到nginx的安装环境中,也就是说我们可以直接使用这些指令。

  1. gzip指令:该指令用于开启或者关闭gzip功能
语法gzip on|off;
默认值gzip off;
位置http、server、location…

注意只有该指令为打开状态,下面的指令才有效果

http{gzip on;
}
  1. gzip_types指令:该指令可以根据响应页的MIME类型选择性地开启Gzip压缩功能
语法gzip_types mime-type …;
默认值gzip_types text/html;
位置http、server、location

所选择的值可以从mime.types文件中进行查找,也可以使用"*"代表所有。

http{gzip_types application/javascript;
}
  1. gzip_comp_level指令:该指令用于设置Gzip压缩程度,级别从1-9,1表示要是程度最低,要是效率最高,9刚好相反,压缩程度最高,但是效率最低最费时间。
语法gzip_comp_level level;
默认值gzip_comp_level 1;
位置http、server、location
http{gzip_comp_level 6;
}
  1. gzip_vary指令:该指令用于设置使用Gzip进行压缩发送是否携带“Vary:Accept-Encoding”头域的响应头部。主要是告诉接收方,所发送的数据经过了Gzip压缩处理
语法gzip_vary on|off;
默认值gzip_vary off;
位置http、server、location
  1. gzip_buffers指令:该指令用于处理请求压缩的缓冲区数量和大小。
语法gzip_buffers number size;
默认值gzip_buffers 32 4k|16 8k;
位置http、server、location

其中number:指定Nginx服务器向系统申请缓存空间个数,size指的是每个缓存空间的大小。主要实现的是申请number个每个大小为size的内存空间。这个值的设定一般会和服务器的操作系统有关,所以建议此项不设置,使用默认值即可。

gzip_buffers 4 16K;	  #缓存空间大小
  1. gzip_disable指令:针对不同种类客户端发起的请求,可以选择性地开启和关闭Gzip功能。
语法gzip_disable regex …;
默认值
位置http、server、location

regex:根据客户端的浏览器标志(user-agent)来设置,支持使用正则表达式。指定的浏览器标志不使用Gzip.该指令一般是用来排除一些明显不支持Gzip的浏览器。

gzip_disable "MSIE [1-6]\.";
  1. gzip_http_version指令:针对不同的HTTP协议版本,可以选择性地开启和关闭Gzip功能。
语法gzip_http_version 1.0|1.1;
默认值gzip_http_version 1.1;
位置http、server、location

该指令是指定使用Gzip的HTTP最低版本,该指令一般采用默认值即可。

  1. gzip_min_length指令:该指令针对传输数据的大小,可以选择性地开启和关闭Gzip功能
语法gzip_min_length length;
默认值gzip_min_length 20;
位置http、server、location
nignx计量大小的单位:bytes[字节] / kb[千字节] / M[兆]
例如: 1024 / 10k|K / 10m|M

Gzip压缩功能对大数据的压缩效果明显,但是如果要压缩的数据比较小的化,可能出现越压缩数据量越大的情况,因此我们需要根据响应内容的大小来决定是否使用Gzip功能,响应页面的大小可以通过头信息中的Content-Length来获取。但是如何使用了Chunk编码动态压缩,该指令将被忽略。建议设置为1K或以上。

  1. gzip_proxied指令:该指令设置是否对服务端返回的结果进行Gzip压缩。
语法gzip_proxied off|expired|no-cache|
no-store|private|no_last_modified|no_etag|auth|any;
默认值gzip_proxied off;
位置http、server、location

off - 关闭Nginx服务器对后台服务器返回结果的Gzip压缩
expired - 启用压缩,如果header头中包含 “Expires” 头信息
no-cache - 启用压缩,如果header头中包含 “Cache-Control:no-cache” 头信息
no-store - 启用压缩,如果header头中包含 “Cache-Control:no-store” 头信息
private - 启用压缩,如果header头中包含 “Cache-Control:private” 头信息
no_last_modified - 启用压缩,如果header头中不包含 “Last-Modified” 头信息
no_etag - 启用压缩 ,如果header头中不包含 “ETag” 头信息
auth - 启用压缩 , 如果header头中包含 “Authorization” 头信息
any - 无条件启用压缩

2、Gzip压缩功能的实例配置

gzip on;  			  #开启gzip功能
gzip_types *;		  #压缩源文件类型,根据具体的访问资源类型设定
gzip_comp_level 6;	  #gzip压缩级别
gzip_min_length 1024; #进行压缩响应页面的最小长度,content-length
gzip_buffers 4 16K;	  #缓存空间大小
gzip_http_version 1.1; #指定压缩响应所需要的最低HTTP请求版本
gzip_vary  on;		  #往头信息中添加压缩标识
gzip_disable "MSIE [1-6]\."; #对IE6以下的版本都不进行压缩
gzip_proxied  off; #nginx作为反向代理压缩服务端返回数据的条件

这些配置在很多地方可能都会用到,所以我们可以将这些内容抽取到一个配置文件中,然后通过include指令把配置文件再次加载到nginx.conf配置文件中,方法使用。

nginx_gzip.conf

gzip on;
gzip_types *;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_buffers 4 16K;
gzip_http_version 1.1;
gzip_vary  on;
gzip_disable "MSIE [1-6]\.";
gzip_proxied  off;

nginx.conf

include nginx_gzip.conf

3、Gzip和sendfile共存问题

前面在讲解sendfile的时候,提到过,开启sendfile以后,在读取磁盘上的静态资源文件的时候,可以减少拷贝的次数,可以不经过用户进程将静态文件通过网络设备发送出去,但是Gzip要想对资源压缩,是需要经过用户进程进行操作的。所以如何解决两个设置的共存问题。

可以使用ngx_http_gzip_static_module模块的gzip_static指令来解决。

(1)、gzip_static指令
gzip_static: 检查与访问资源同名的.gz文件时,response中以gzip相关的header返回.gz文件的内容。

语法gzip_static on | off | always;
默认值gzip_static off;
位置http、server、location

添加上述命令后,会报一个错误,unknown directive "gzip_static"主要的原因是Nginx默认是没有添加ngx_http_gzip_static_module模块。如何来添加?
(2)、添加模块到Nginx的实现步骤
(1)查询当前Nginx的配置参数

nginx -V

(2)将nginx安装目录下sbin目录中的nginx二进制文件进行更名

cd /usr/local/nginx/sbin
mv nginx nginxold

(3) 进入Nginx的安装目录

cd /root/nginx/core/nginx-1.16.1

(4)执行make clean清空之前编译的内容

make clean

(5)使用configure来配置参数

./configure --with-http_gzip_static_module

(6)使用make命令进行编译

make

(7) 将objs目录下的nginx二进制执行文件移动到nginx安装目录下的sbin目录中

mv objs/nginx /usr/local/nginx/sbin

(8)执行更新命令

make upgrade

4、gzip_static测试使用

(1)直接访问http://192.168.200.133/jquery.js
(2)使用gzip命令进行压缩

cd /usr/local/nginx/html
gzip jquery.js

(3)再次访问http://192.168.200.133/jquery.js

5、静态资源的缓存处理

(1)、什么是缓存

缓存(cache),原始意义是指访问速度比一般随机存取存储器(RAM)快的一种高速存储器,通常它不像系统主存那样使用DRAM技术,而使用昂贵但较快速的SRAM技术。
缓存的设置是所有现代计算机系统发挥高性能的重要因素之一。

(2)、什么是web缓存

Web缓存是指一个Web资源(如html页面,图片,js,数据等)存在于Web服务器和客户端(浏览器)之间的副本。缓存会根据进来的请求保存输出内容的副本;
当下一个请求来到的时候,如果是相同的URL,缓存会根据缓存机制决定是直接使用副本响应访问请求,还是向源服务器再次发送请求。
比较常见的就是浏览器会缓存访问过网站的网页,当再次访问这个URL地址的时候,如果网页没有更新,就不会再次下载网页,而是直接使用本地缓存的网页。
只有当网站明确标识资源已经更新,浏览器才会再次下载网页

(3)、web缓存的种类

客户端缓存浏览器缓存
服务端缓存Nginx / Redis / Memcached等

(4)、浏览器缓存

是为了节约网络的资源加速浏览,浏览器在用户磁盘上对最近请求过的文档进行存储,当访问者再次请求这个页面时,
浏览器就可以从本地磁盘显示文档,这样就可以加速页面的阅览.

(5)、为什么要用浏览器缓存

成本最低的一种缓存实现
减少网络带宽消耗
降低服务器压力
减少网络延迟,加快页面打开速度

(6)、浏览器缓存的执行流程

HTTP协议中和页面缓存相关的字段,我们先来认识下:

header说明
Expires缓存过期的日期和时间
Cache-Control设置和缓存相关的配置信息
Last-Modified请求资源最后修改时间
ETag请求变量的实体标签的当前值,比如文件的MD5值

在这里插入图片描述

(1)用户首次通过浏览器发送请求到服务端获取数据,客户端是没有对应的缓存,所以需要发送request请求来获取数据;

(2)服务端接收到请求后,获取服务端的数据及服务端缓存的允许后,返回200的成功状态码并且在响应头上附上对应资源以及缓存信息;

(3)当用户再次访问相同资源的时候,客户端会在浏览器的缓存目录中查找是否存在响应的缓存文件

(4)如果没有找到对应的缓存文件,则走(2)步

(5)如果有缓存文件,接下来对缓存文件是否过期进行判断,过期的判断标准是(Expires),

(6)如果没有过期,则直接从本地缓存中返回数据进行展示

(7)如果Expires过期,接下来需要判断缓存文件是否发生过变化

(8)判断的标准有两个,一个是ETag(Entity Tag),一个是Last-Modified

(9)判断结果是未发生变化,则服务端返回304,直接从缓存文件中获取数据

(10)如果判断是发生了变化,重新从服务端获取数据,并根据缓存协商(服务端所设置的是否需要进行缓存数据的设置)来进行数据缓存。

6、浏览器缓存相关指令

Nginx需要进行缓存相关设置,就需要用到如下的指令
(1)、expires指令

expires:该指令用来控制页面缓存的作用。可以通过该指令控制HTTP应答中的“Expires"和”Cache-Control"

语法expires [modified] time
expires epoch|max|off;
默认值expires off;
位置http、server、location

time:可以整数也可以是负数,指定过期时间,如果是负数,Cache-Control则为no-cache,如果为整数或0,则Cache-Control的值为max-age=time;

epoch: 指定Expires的值为’1 January,1970,00:00:01 GMT’(1970-01-01 00:00:00),Cache-Control的值no-cache

max:指定Expires的值为’31 December2037 23:59:59GMT’ (2037-12-31 23:59:59) ,Cache-Control的值为10年

off:默认不缓存。
(2)、add_header指令

add_header指令是用来添加指定的响应头和响应值。

语法add_header name value [always];
默认值
位置http、server、location…

Cache-Control作为响应头信息,可以设置如下值:

缓存响应指令:

Cache-control: must-revalidate
Cache-control: no-cache
Cache-control: no-store
Cache-control: no-transform
Cache-control: public
Cache-control: private
Cache-control: proxy-revalidate
Cache-Control: max-age=
Cache-control: s-maxage=
指令说明
must-revalidate可缓存但必须再向源服务器进行确认
no-cache缓存前必须确认其有效性
no-store不缓存请求或响应的任何内容
no-transform代理不可更改媒体类型
public可向任意方提供响应的缓存
private仅向特定用户返回响应
proxy-revalidate要求中间缓存服务器对缓存的响应有效性再进行确认
max-age=<秒>响应最大Age值
s-maxage=<秒>公共缓存服务器响应的最大Age值

max-age=[秒]:

7、静态资源防盗链

(1)、什么是资源盗链

资源盗链指的是此内容不在自己服务器上,而是通过技术手段,绕过别人的限制将别人的内容放到自己页面上最终展示给用户。以此来盗取大网站的空间和流量。简而言之就是用别人的东西成就自己的网站。

比如在html里面写俩image标签,引入京东或者百度的图片,可以看到,京东没有防盗链,可以直接加载出图片,而百度的图片无法正常显示:
在这里插入图片描述

(2)、Nginx防盗链的实现原理:

了解防盗链的原理之前,我们得先学习一个HTTP的头信息Referer,当浏览器向web服务器发送请求的时候,一般都会带上Referer,来告诉浏览器该网页是从哪个页面链接过来的。
后台服务器可以根据获取到的这个Referer信息来判断是否为自己信任的网站地址,如果是则放行继续访问,如果不是则可以返回403(服务端拒绝访问)的状态信息。

Nginx防盗链的具体实现:
valid_referers:nginx会通就过查看referer自动和valid_referers后面的内容进行匹配,如果匹配到了就将$invalid_referer变量置0,如果没有匹配到,则将$invalid_referer变量置为1,匹配的过程中不区分大小写。

语法valid_referers none|blocked|server_names|string…
默认值
位置server、location

none: 如果Header中的Referer为空,允许访问

blocked:在Header中的Referer不为空,但是该值被防火墙或代理进行伪装过,如不带"http://" 、"https://"等协议头的资源允许访问。

server_names:指定具体的域名或者IP

string: 可以支持正则表达式和*的字符串。如果是正则表达式,需要以~开头表示,例如

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;}

(3)、针对目录进行防盗链
遇到的问题:图片有很多,该如何批量进行防盗链?
配置如下:

location /images {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;
}

这样我们可以对一个目录下的所有资源进行翻到了操作。

遇到的问题:Referer的限制比较粗,比如随意加一个Referer,上面的方式是无法进行限制的。那么这个问题改如何解决?

此处我们需要用到Nginx的第三方模块ngx_http_accesskey_module,第三方模块如何实现盗链,如果在Nginx中使用第三方模块的功能,这些我们在后面的Nginx的模块篇再进行详细的讲解。

(4)、防盗重写为自定义图片

防盗链之前我们已经介绍过了相关的知识,在rewrite中的防盗链和之前将的原理其实都是一样的,只不过通过rewrite可以将防盗链的功能进行完善下,当出现防盗链的情况,我们可以使用rewrite将请求转发到自定义的一张图片和页面,给用户比较好的提示信息。下面我们就通过根据文件类型实现防盗链的一个配置实例:

location /images {root html;valid_referers none blocked www.baidu.com;if ($invalid_referer){#return 403;rewrite ^/    /images/forbidden.png break;}
}

8、spenssl生成证书

1、先要确认当前系统是否有安装openssl

openssl version

安装下面的命令进行生成

mkdir /root/cert
cd /root/cert
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

2、开启SSL实例

server {listen       443 ssl;server_name  localhost;ssl_certificate      server.cert;ssl_certificate_key  server.key;ssl_session_cache    shared:SSL:1m;ssl_session_timeout  5m;ssl_ciphers  HIGH:!aNULL:!MD5;ssl_prefer_server_ciphers  on;location / {root   html;index  index.html index.htm;}
}

五、nginx反向代理

1、proxy_pass

正向代理代理的对象是客户端,反向代理代理的是服务端,Nginx即可以实现正向代理,也可以实现反向代理
在编写proxy_pass的时候,后面的值要不要加"/"?
接下来通过例子来说明刚才我们提到的问题:

该指令用来设置被代理服务器地址,可以是主机名称、IP地址加端口号形式。

语法proxy_pass URL;
默认值
位置location

URL:为要设置的被代理服务器地址,包含传输协议(http,https://)、主机名称或IP地址加端口号、URI等要素。

server {listen 80;server_name localhost;location /{#proxy_pass http://192.168.200.146;proxy_pass http://192.168.200.146/;}
}
当客户端访问 http://localhost/index.html,效果是一样的
server{listen 80;server_name localhost;location /server{#proxy_pass http://192.168.200.146;proxy_pass http://192.168.200.146/;}
}
当客户端访问 http://localhost/server/index.html
这个时候,第一个proxy_pass就变成了http://localhost/server/index.html
第二个proxy_pass就变成了http://localhost/index.html效果就不一样了。

2、proxy_set_header

该指令可以更改Nginx服务器接收到的客户端请求的请求头信息,然后将新的请求头发送给代理的服务器

语法proxy_set_header field value;
默认值proxy_set_header Host $proxy_host;
proxy_set_header Connection close;
位置http、server、location

需要注意的是,如果想要看到结果,必须在被代理的服务器上来获取添加的头信息。
被代理服务器: [192.168.200.146]

server {listen  8080;server_name localhost;default_type text/plain;return 200 $http_username;
}

代理服务器: [192.168.200.133]

server {listen  8080;server_name localhost;location /server {proxy_pass http://192.168.200.146:8080/;proxy_set_header username TOM;}}

3、proxy_redirect

该指令是用来重置头信息中的"Location"和"Refresh"的值。

语法proxy_redirect redirect replacement;
proxy_redirect default;
proxy_redirect off;
默认值proxy_redirect default;
位置http、server、location

》为什么要用该指令?

服务端[192.168.200.146]

server {listen  8081;server_name localhost;if (!-f $request_filename){return 302 http://192.168.200.146;}
}

代理服务端[192.168.200.133]

server {listen  8081;server_name localhost;location / {proxy_pass http://192.168.200.146:8081/;proxy_redirect http://192.168.200.146 http://192.168.200.133;}
}

》该指令的几组选项

proxy_redirect redirect replacement;

redirect:目标,Location的值
replacement:要替换的值

proxy_redirect default;

default;
将location块的uri变量作为replacement,
将proxy_pass变量作为redirect进行替换

proxy_redirect off;

关闭proxy_redirect的功能

4、nginx反向代理实战

在这里插入图片描述
服务器1,2,3存在两种情况

第一种情况: 三台服务器的内容不一样。
第二种情况: 三台服务器的内容是一样。
  1. 如果服务器1、服务器2和服务器3的内容不一样,那我们可以根据用户请求来分发到不同的服务器。
代理服务器
server {listen          8082;server_name     localhost;location /server1 {proxy_pass http://192.168.200.146:9001/;}location /server2 {proxy_pass http://192.168.200.146:9002/;}location /server3 {proxy_pass http://192.168.200.146:9003/;}
}服务端
server1
server {listen          9001;server_name     localhost;default_type text/html;return 200 '

192.168.200.146:9001

' } server2 server {listen 9002;server_name localhost;default_type text/html;return 200 '

192.168.200.146:9002

' } server3 server {listen 9003;server_name localhost;default_type text/html;return 200 '

192.168.200.146:9003

' }
  1. 如果服务器1、服务器2和服务器3的内容是一样的,该如何处理?
    解决:nginx负载均衡

六、负载均衡

1、负载均衡的作用

1、解决服务器的高并发压力,提高应用程序的处理性能。

2、提供故障转移,实现高可用。

3、通过添加或减少服务器数量,增强网站的可扩展性。

4、在负载均衡器上进行过滤,可以提高系统的安全性。

2、Nginx七层负载均衡

Nginx要实现七层负载均衡需要用到proxy_pass代理模块配置。Nginx默认安装支持这个模块,我们不需要再做任何处理。Nginx的负载均衡是在Nginx的反向代理基础上把用户的请求根据指定的算法分发到一组【upstream虚拟服务池】。

3、Nginx七层负载均衡的指令

1、upstream指令

该指令是用来定义一组服务器,它们可以是监听不同端口的服务器,并且也可以是同时监听TCP和Unix socket的服务器。服务器可以指定不同的权重,默认为1。

语法upstream name {…}
默认值
位置http

2、server指令

该指令用来指定后端服务器的名称和一些参数,可以使用域名、IP、端口或者unix socket

语法server name [paramerters]
默认值
位置upstream

3、down指令
down:将该服务器标记为永久不可用,那么该代理服务器将不参与负载均衡。

upstream backend{server 192.168.200.146:9001 down;server 192.168.200.146:9002server 192.168.200.146:9003;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

该状态一般会对需要停机维护的服务器进行设置。
4、backup指令
backup:将该服务器标记为备份服务器,当主服务器不可用时,将用来传递请求。

upstream backend{server 192.168.200.146:9001 down;server 192.168.200.146:9002 backup;server 192.168.200.146:9003;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

5、max_conns

max_conns=number:用来设置代理服务器同时活动链接的最大数量,默认为0,表示不限制,使用该配置可以根据后端服务器处理请求的并发量来进行设置,防止后端服务器被压垮。

6、max_fails和fail_timeout
max_fails=number:设置允许请求代理服务器失败的次数,默认为1。
fail_timeout=time:设置经过max_fails失败后,服务暂停的时间,默认是10秒。

upstream backend{server 192.168.200.133:9001 down;server 192.168.200.133:9002 backup;server 192.168.200.133:9003 max_fails=3 fail_timeout=15;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

4、负载均衡(轮询访问)案例

服务端设置

server {listen   9001;server_name localhost;default_type text/html;location /{return 200 '

192.168.200.146:9001

';} } server {listen 9002;server_name localhost;default_type text/html;location /{return 200 '

192.168.200.146:9002

';} } server {listen 9003;server_name localhost;default_type text/html;location /{return 200 '

192.168.200.146:9003

';} }

负载均衡器设置

upstream backend{server 192.168.200.146:9091;server 192.168.200.146:9092;server 192.168.200.146:9093;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

5、负载均衡状态

代理服务器在负责均衡调度中的状态有以下几个:

状态概述
down当前的server暂时不参与负载均衡
backup预留的备份服务器
max_fails允许请求失败的次数
fail_timeout经过max_fails失败后, 服务暂停时间
max_conns限制最大的接收连接数

6、负载均衡策略

介绍完Nginx负载均衡的相关指令后,我们已经能实现将用户的请求分发到不同的服务器上,那么除了采用默认的分配方式以外,我们还能采用什么样的负载算法?

Nginx的upstream支持如下六种方式的分配算法,分别是:

算法名称说明
轮询默认方式
weight权重方式
ip_hash依据ip分配方式
least_conn依据最少连接方式
url_hash依据URL分配方式
fair依据响应时间方式

1、weight加权[加权轮询]

weight=number:用来设置服务器的权重,默认为1,权重数据越大,被分配到请求的几率越大;该权重值,主要是针对实际工作环境中不同的后端服务器硬件配置进行调整的,所有此策略比较适合服务器的硬件配置差别比较大的情况。

upstream backend{server 192.168.200.146:9001 weight=10;server 192.168.200.146:9002 weight=5;server 192.168.200.146:9003 weight=3;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

2、ip_hash
当对后端的多台动态应用服务器做负载均衡时,ip_hash指令能够将某个客户端IP的请求通过哈希算法定位到同一台后端服务器上。这样,当来自某一个IP的用户在后端Web服务器A上登录后,在访问该站点的其他URL,能保证其访问的还是后端web服务器A。

语法ip_hash;
默认值
位置upstream
upstream backend{ip_hash;server 192.168.200.146:9001;server 192.168.200.146:9002;server 192.168.200.146:9003;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

需要额外多说一点的是使用ip_hash指令无法保证后端服务器的负载均衡,可能导致有些后端服务器接收到的请求多,有些后端服务器接收的请求少,而且设置后端服务器权重等方法将不起作用。
3、least_conn

最少连接,把请求转发给连接数较少的后端服务器。轮询算法是把请求平均的转发给各个后端,使它们的负载大致相同;但是,有些请求占用的时间很长,会导致其所在的后端负载较高。这种情况下,least_conn这种方式就可以达到更好的负载均衡效果。

upstream backend{least_conn;server 192.168.200.146:9001;server 192.168.200.146:9002;server 192.168.200.146:9003;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

此负载均衡策略适合请求处理时间长短不一造成服务器过载的情况。

4、url_hash
按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,要配合缓存命中来使用。同一个资源多次请求,可能会到达不同的服务器上,导致不必要的多次下载,缓存命中率不高,以及一些资源时间的浪费。而使用url_hash,可以使得同一个url(也就是同一个资源请求)会到达同一台服务器,一旦缓存住了资源,再此收到请求,就可以从缓存中读取。

upstream backend{hash &request_uri;server 192.168.200.146:9001;server 192.168.200.146:9002;server 192.168.200.146:9003;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

访问如下地址:

http://192.168.200.133:8083/a
http://192.168.200.133:8083/b
http://192.168.200.133:8083/c

5、fair,智能分配

fair采用的不是内建负载均衡使用的轮换的均衡算法,而是可以根据页面大小、加载时间长短智能的进行负载均衡。那么如何使用第三方模块的fair负载均衡策略。

upstream backend{fair;server 192.168.200.146:9001;server 192.168.200.146:9002;server 192.168.200.146:9003;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

但是如何直接使用会报错,因为fair属于第三方模块实现的负载均衡。需要添加nginx-upstream-fair,如何添加对应的模块:

  1. 下载nginx-upstream-fair模块
下载地址为:https://github.com/gnosek/nginx-upstream-fair
  1. 将下载的文件上传到服务器并进行解压缩
unzip nginx-upstream-fair-master.zip
  1. 重命名资源
mv nginx-upstream-fair-master fair
  1. 使用./configure命令将资源添加到Nginx模块中
./configure --add-module=/root/fair
  1. 编译
make

编译可能会出现如下错误,ngx_http_upstream_srv_conf_t结构中缺少default_port

解决方案:

在Nginx的源码中 src/http/ngx_http_upstream.h,找到ngx_http_upstream_srv_conf_s,在模块中添加添加default_port属性

in_port_t	   default_port

然后再进行make.

  1. 更新Nginx

6.1 将sbin目录下的nginx进行备份

mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginxold

6.2 将安装目录下的objs中的nginx拷贝到sbin目录

cd objs
cp nginx /usr/local/nginx/sbin

​ 6.3 更新Nginx

cd ../
make upgrade
  1. 编译测试使用Nginx

上面介绍了Nginx常用的负载均衡的策略,有人说是5种,是把轮询和加权轮询归为一种,也有人说是6种。那么在咱们以后的开发中到底使用哪种,这个需要根据实际项目的应用场景来决定的。

7、负载均衡案例

1、案例一:对所有请求实现一般轮询规则的负载均衡

upstream backend{server 192.168.200.146:9001;server 192.168.200.146:9002;server 192.168.200.146:9003;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

2、案例二:对所有请求实现加权轮询规则的负载均衡

upstream backend{server 192.168.200.146:9001 weight=7;server 192.168.200.146:9002 weight=5;server 192.168.200.146:9003 weight=3;
}
server {listen 8083;server_name localhost;location /{proxy_pass http://backend;}
}

3、案例三:对特定资源实现负载均衡

upstream videobackend{server 192.168.200.146:9001;server 192.168.200.146:9002;
}
upstream filebackend{server 192.168.200.146:9003;server 192.168.200.146:9004;
}
server {listen 8084;server_name localhost;location /video/ {proxy_pass http://videobackend;}location /file/ {proxy_pass http://filebackend;}
}

4、案例四:对不同域名实现负载均衡

upstream itcastbackend{server 192.168.200.146:9001;server 192.168.200.146:9002;
}
upstream itheimabackend{server 192.168.200.146:9003;server 192.168.200.146:9004;
}
server {listen	8085;server_name www.itcast.cn;location / {proxy_pass http://itcastbackend;}
}
server {listen	8086;server_name www.itheima.cn;location / {proxy_pass http://itheimabackend;}
}

5、案例五:实现带有URL重写的负载均衡

upstream backend{server 192.168.200.146:9001;server 192.168.200.146:9002;server 192.168.200.146:9003;
}
server {listen	80;server_name localhost;location /file/ {rewrite ^(/file/.*) /server/$1 last;}location / {proxy_pass http://backend;}
}

6、案例六,实现下图效果
在这里插入图片描述
nginx.conf配置

stream {upstream redisbackend {server 192.168.200.146:6379;server 192.168.200.146:6378;}upstream tomcatbackend {server 192.168.200.146:8080;}server {listen  81;proxy_pass redisbackend;}server {listen	82;proxy_pass tomcatbackend;}
}

八、缓存集成

缓存的概念:缓存就是数据交换的缓冲区(称作:Cache),当用户要获取数据的时候,会先从缓存中去查询获取数据,如果缓存中有就会直接返回给用户,如果缓存中没有,则会发请求从服务器重新查询数据,将数据返回给用户的同时将数据放入缓存,下次用户就会直接从缓存中获取数据。

1、Nginx缓存设置的相关指令

Nginx的web缓存服务主要是使用ngx_http_proxy_module模块相关指令集来完成,接下来我们把常用的指令来进行介绍下。
1、proxy_cache_path

该指定用于设置缓存文件的存放路径

语法proxy_cache_path path [levels=number]
keys_zone=zone_name:zone_size [inactive=time][max_size=size];
默认值
位置http

path:缓存路径地址,如:

/usr/local/proxy_cache

levels: 指定该缓存空间对应的目录,最多可以设置3层,每层取值为1|2如 :

levels=1:2   缓存空间有两层目录,第一次是1个字母,第二次是2个字母
举例说明:
itheima[key]通过MD5加密以后的值为 43c8233266edce38c2c9af0694e2107d
levels=1:2   最终的存储路径为/usr/local/proxy_cache/d/07
levels=2:1:2 最终的存储路径为/usr/local/proxy_cache/7d/0/21
levels=2:2:2 最终的存储路径为??/usr/local/proxy_cache/7d/10/e2

keys_zone:用来为这个缓存区设置名称和指定大小,如:

keys_zone=itcast:200m  缓存区的名称是itcast,大小为200M,1M大概能存储8000个keys

inactive:指定缓存的数据多次时间未被访问就将被删除,如:

inactive=1d   缓存数据在1天内没有被访问就会被删除

max_size:设置最大缓存空间,如果缓存空间存满,默认会覆盖缓存时间最长的资源,如:

max_size=20g

配置实例:

http{proxy_cache_path /usr/local/proxy_cache keys_zone=itcast:200m  levels=1:2:1 inactive=1d max_size=20g;
}

2、proxy_cache

该指令用来开启或关闭代理缓存,如果是开启则自定使用哪个缓存区来进行缓存。

语法proxy_cache zone_name|off;
默认值proxy_cache off;
位置http、server、location

zone_name:指定使用缓存区的名称
3、proxy_cache_key

该指令用来设置web缓存的key值,Nginx会根据key值MD5哈希存缓存。

语法proxy_cache_key key;
默认值proxy_cache_key $scheme$proxy_host$request_uri;
位置http、server、location

4、proxy_cache_valid

该指令用来对不同返回状态码的URL设置不同的缓存时间

语法proxy_cache_valid [code …] time;
默认值
位置http、server、location

如:

proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
为200和302的响应URL设置10分钟缓存,为404的响应URL设置1分钟缓存
proxy_cache_valid any 1m;
对所有响应状态码的URL都设置1分钟缓存

5、proxy_cache_min_uses

该指令用来设置资源被访问多少次后被缓存

语法proxy_cache_min_uses number;
默认值proxy_cache_min_uses 1;
位置http、server、location

6、proxy_cache_methods

该指令用户设置缓存哪些HTTP方法

语法proxy_cache_methods GET|HEAD|POST;
默认值proxy_cache_methods GET HEAD;
位置http、server、location

默认缓存HTTP的GET和HEAD方法,不缓存POST方法。

2、Nginx缓存设置案例

在这里插入图片描述

1.环境准备

应用服务器的环境准备

(1)在192.168.200.146服务器上的tomcat的webapps下面添加一个js目录,并在js目录中添加一个jquery.js文件

(2)启动tomcat

(3)访问测试

http://192.168.200.146:8080/js/jquery.js

Nginx的环境准备

(1)完成Nginx反向代理配置

http{upstream backend{server 192.168.200.146:8080;}server {listen       8080;server_name  localhost;location / {proxy_pass http://backend/js/;}}
}

(2)完成Nginx缓存配置

4.添加缓存配置

http{proxy_cache_path /usr/local/proxy_cache levels=2:1 keys_zone=itcast:200m inactive=1d max_size=20g;upstream backend{server 192.168.200.146:8080;}server {listen       8080;server_name  localhost;location / {proxy_cache itcast;proxy_cache_key itheima;#这里建议用  proxy_cache_key $scheme$proxy_host$request_uri; 来动态设置keyproxy_cache_min_uses 5;proxy_cache_valid 200 5d;proxy_cache_valid 404 30s;proxy_cache_valid any 1m;add_header nginx-cache "$upstream_cache_status";proxy_pass http://backend/js/;}}
}

3、Nginx缓存的清除

1、方式一:删除对应的缓存目录

rm -rf /usr/local/proxy_cache/......

2、方式二:使用第三方扩展模块: ngx_cache_purge

(1)下载ngx_cache_purge模块对应的资源包,并上传到服务器上。

ngx_cache_purge-2.3.tar.gz

(2)对资源文件进行解压缩

tar -zxf ngx_cache_purge-2.3.tar.gz

(3)修改文件夹名称,方便后期配置

mv ngx_cache_purge-2.3 purge

(4)查询Nginx的配置参数

nginx -V

(5)进入Nginx的安装目录,使用./configure进行参数配置

./configure --add-module=/root/nginx/module/purge

(6)使用make进行编译

make

(7)将nginx安装目录的nginx二级制可执行文件备份

mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginxold

(8)将编译后的objs中的nginx拷贝到nginx的sbin目录下

cp objs/nginx /usr/local/nginx/sbin

(9)使用make进行升级

make upgrade

(10)在nginx配置文件中进行如下配置

server{location ~/purge(/.*) {proxy_cache_purge itcast itheima;}
}

4、Nginx设置资源不缓存

前面咱们已经完成了Nginx作为web缓存服务器的使用。但是我们得思考一个问题就是不是所有的数据都适合进行缓存。比如说对于一些经常发生变化的数据。如果进行缓存的话,就很容易出现用户访问到的数据不是服务器真实的数据。所以对于这些资源我们在缓存的过程中就需要进行过滤,不进行缓存。

1、Nginx也提供了这块的功能设置,需要使用到如下两个指令。(官方推荐配置的时候下面两个指令最好都配上)

(1)、proxy_no_cache

该指令是用来定义不将数据进行缓存的条件。

语法proxy_no_cache string …;
默认值
位置http、server、location

配置实例

proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;

(2)、proxy_cache_bypass

该指令是用来设置不从缓存中获取数据的条件。

语法proxy_cache_bypass string …;
默认值
位置http、server、location

配置实例

proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;

上述两个指令都有一个指定的条件,这个条件可以是多个,并且多个条件中至少有一个不为空且不等于"0",则条件满足成立。上面给的配置实例是从官方网站获取的,里面使用到了三个变量,分别是$cookie_nocache、$arg_nocache、$arg_comment

$cookie_nocache、\$arg_nocache、\$arg_comment
这三个参数分别代表的含义是:

$cookie_nocache
指的是当前请求的cookie中键的名称为nocache对应的值
$arg_nocache和$arg_comment
指的是当前请求的参数中属性名为nocache和comment对应的属性值

案例演示下:

log_format params $cookie_nocache | $arg_nocache | $arg_comment;
server{listen	8081;server_name localhost;location /yyy{access_log logs/access_params.log params;add_header Set-Cookie 'nocache=999'; #$cookie_nocache在这里定义root html;index index.html;}
}

此时访问http://localhost:8081/yyy因为路径添加了cookie_nocache请求头,所以不会缓存;
或者http://localhost:8081/xxx?nocache=123或者http://localhost:8081/xxx?comment=123只要nocache、comment不为空,就不会缓存
2、案例实现
设置不缓存资源的配置方案,所有的.js文件都不缓存

server{listen	8080;server_name localhost;location / {if ($request_uri ~ /.*\.js$){ #判断是否为js文件set $nocache 1;  #自动设置参数 nocache 不为0}proxy_no_cache $nocache $cookie_nocache $arg_nocache $arg_comment;proxy_cache_bypass $nocache $cookie_nocache $arg_nocache $arg_comment;}
}

九、实战:Nginx实现服务器端集群搭建

Nginx实现服务器端集群搭建

十、下面补充几个nginx的置nginx.conf模板

nginx反向代理


#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {worker_connections  1024;
}http {include       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  logs/access.log  main;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;#gzip  off;#开启压缩,增加网页加载速度gzip on;gzip_min_length 1k; #不压缩临界值,大于1K的才压缩,一般不用改gzip_buffers 4 16k; gzip_http_version 1.0; #gzip_comp_level 2; #压缩级别,1-10,数字越大压缩的越好,时间也越长,看心情随便改吧gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;gzip_vary off;gzip_disable "MSIE [1-6]\.";	#IE6对Gzip不怎么友好,不给它Gzip了#服务器的集群  upstream  wssp.com {  #服务器集群名字   #服务器配置   weight是权重的意思,权重越大,分配的概率越大。server  localhost:12010 weight=1 fail_timeout=1s;}server {listen       12002;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  main;location /api/ {proxy_pass http://wssp.com/;proxy_connect_timeout       1;#连接超时时间#获取客户端真实ipproxy_set_header        Host            $host;proxy_set_header        X-Real-IP       $remote_addr;proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;}location / {root   html/dist;#try_files $uri $uri/ @router; #前端采用history去掉了'#',nginx因此配置相应路由try_files $uri $uri/ /index.html;     #4.重定向,内部文件的指向(照写)index  index.html;}#多个项目部署不要默认静态资源加载,因为不同的项目资源路径不同#location ~ .*\.(css|js|jpg|png|gif)$ {  #root html\WeChatHtml;  #root html\dist; #expires 30d;#access_log off;#}#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   html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {#    proxy_pass   http://127.0.0.1;#}# 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##location ~ /\.ht {#    deny  all;#}}# another virtual host using mix of IP-, name-, and port-based configuration##server {#    listen       8000;#    listen       somename:8080;#    server_name  somename  alias  another.alias;#    location / {#        root   html;#        index  index.html index.htm;#    }#}# HTTPS server##server {#    listen       443 ssl;#    server_name  localhost;#    ssl_certificate      cert.pem;#    ssl_certificate_key  cert.key;#    ssl_session_cache    shared:SSL:1m;#    ssl_session_timeout  5m;#    ssl_ciphers  HIGH:!aNULL:!MD5;#    ssl_prefer_server_ciphers  on;#    location / {#        root   html;#        index  index.html index.htm;#    }#}}

模板二


#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {worker_connections  1024;
}http {include       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  logs/access.log  main;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;#gzip  on;server {listen       80;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  mainlocation / {root   /usr/local/project/webBack;index  index.html index.htm;try_files $uri $uri/ @router;  #注意此处:配置@router后刷新地址不会出现404}location @router {rewrite ^.*$ /index.html last;}location /sysApi/ {proxy_pass http://localhost:10002/;}#location /chartApi/ {#proxy_pass http://localhost:8862/;#}#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   html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {#    proxy_pass   http://127.0.0.1;#}# 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##location ~ /\.ht {#    deny  all;#}}# another virtual host using mix of IP-, name-, and port-based configuration##server {#    listen       8000;#    listen       somename:8080;#    server_name  somename  alias  another.alias;#    location / {#        root   html;#        index  index.html index.htm;#    }#}# HTTPS server##server {#    listen       443 ssl;#    server_name  localhost;#    ssl_certificate      cert.pem;#    ssl_certificate_key  cert.key;#    ssl_session_cache    shared:SSL:1m;#    ssl_session_timeout  5m;#    ssl_ciphers  HIGH:!aNULL:!MD5;#    ssl_prefer_server_ciphers  on;#    location / {#        root   html;#        index  index.html index.htm;#    }#}
}

nginx负载均衡


#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {worker_connections  1024;
}http {include       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  logs/access.log  main;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;#gzip  on;upstream  furenqiang {  #服务器集群名字   #服务器配置   weight是权重的意思,权重越大,分配的概率越大。server  localhost:10011;}server {listen       88;server_name  furenqiang.com;#charset koi8-r;#access_log  logs/host.access.log  main;location / {proxy_set_header Host $host;proxy_pass http://furenqiang;}#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   html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {#    proxy_pass   http://127.0.0.1;#}# 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##location ~ /\.ht {#    deny  all;#}}# another virtual host using mix of IP-, name-, and port-based configuration##server {#    listen       8000;#    listen       somename:8080;#    server_name  somename  alias  another.alias;#    location / {#        root   html;#        index  index.html index.htm;#    }#}# HTTPS server##server {#    listen       443 ssl;#    server_name  localhost;#    ssl_certificate      cert.pem;#    ssl_certificate_key  cert.key;#    ssl_session_cache    shared:SSL:1m;#    ssl_session_timeout  5m;#    ssl_ciphers  HIGH:!aNULL:!MD5;#    ssl_prefer_server_ciphers  on;#    location / {#        root   html;#        index  index.html index.htm;#    }#}}

nginx配置模板三,设置了nginx的缓存大小

#user  nobody;
worker_processes  1;#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {worker_connections  1024;
}http {include       mime.types;default_type  application/octet-stream;log_format  main  '$remote_addr - $remote_user [$time_local] $http_host$request_uri ''$status $body_bytes_sent ''$upstream_response_time $request_time ';access_log  logs/access2.log  main;proxy_buffer_size 12800k;proxy_buffers 32 6400k;proxy_busy_buffers_size 51200k;sendfile        on;#tcp_nopush     on;#keepalive_timeout  0;keepalive_timeout  65;server {listen       8021;server_name  localhost;client_max_body_size 500M;client_header_buffer_size 51200k; large_client_header_buffers 4 51200k; proxy_buffer_size 12800k; proxy_buffers 8 12800k; fastcgi_buffer_size 51200k; fastcgi_buffers 4 51200k;location /ServiceApply{proxy_pass   http://localhost:5080/ServiceApply/;}location /AnalyEvaluate{proxy_pass   http://localhost:5080/AnalyEvaluate/;}location /IndexModelApply{proxy_pass   http://localhost:5080/IndexModelApply/;}location /LandpotalApply{proxy_pass   http://localhost:5080/LandpotalApply/;}location /StockApply{		    proxy_pass   http://localhost:5080/StockApply/;}location /StandardApply{		    proxy_pass   http://localhost:5080/StandardApply/;}location /MontiorApply{proxy_pass   http://localhost:5080/MontiorApply/;}location /QuotaCalcApply{proxy_pass   http://localhost:5080/QuotaCalcApply/;}location /CapacityApply{proxy_pass   http://localhost:5080/CapacityApply/;}location /AutoLocation{proxy_pass   http://localhost:5080/AutoLocation/;}location /OverlapApply{proxy_pass   http://localhost:5080/OverlapApply/;}location /quality {proxy_pass  http://localhost:8087/;}location /datahub{		    proxy_pass   http://localhost:8300/;}location /analysis-evaluation{proxy_pass   http://localhost:5080/analysis-evaluation/;}location /model{proxy_pass   http://localhost:5080/model/;}location /db-manager{proxy_pass   http://localhost:5080/db-manager/;}location /resource-bear{proxy_pass   http://localhost:5080/resource-bear/;}location /monitor{proxy_pass   http://localhost:5080/monitor/;}location /quality-check{proxy_pass   http://localhost:5080/quality-check/;}location /main{proxy_pass   http://localhost:5080/main/;}location /basic-platform{proxy_pass   http://localhost:5080/basic-platform/;}location /usercent{proxy_pass   http://localhost:5080/usercent/;}location /land-portal{proxy_pass   http://localhost:5080/land-portal/;}location /land{proxy_pass   http://localhost:5080/land/;}location /dataInfo{proxy_pass   http://localhost:8082/api;}location /exchange{proxy_pass   http://localhost:5080/exchange/;}location /webroot{		    proxy_pass   http://localhost:8022/webroot/;}location /terrain{proxy_pass   http://localhost:3000/;}location /ly-nodetest/{proxy_pass   http://localhost:8181/;}location /portal{proxy_pass   http://localhost:8020/portal;}location /vectortile{proxy_pass   http://localhost:8022/vectortile/;}location ^~ /mapserver/ {proxy_pass    http://localhost:8091/mapserver/;}location ^~ /mapserver/raster/ {proxy_pass   http://localhost:8093/mapserver/raster/;}location /catalog{proxy_pass   http://localhost:5080/portal/;}location /user-center{proxy_pass   http://localhost:5080/user-center/;}location /service{proxy_pass   http://localhost:5080/service/;}location /data{proxy_pass   http://localhost:5080/data/;}location /resource{proxy_pass   http://localhost:5080/resource/;}location /highgis-maintence{proxy_pass   http://localhost:5080/highgis-maintence/;}location /template{proxy_pass   http://localhost:5080/template/;}	location /piesat-mapserver{proxy_pass   http://localhost:9200/piesat-mapserver/;}location /sharechange{proxy_pass   http://localhost:5080/sharechange/;}location /upload{proxy_pass   http://localhost:5080/upload/;}}
}

配置模板四,liunx服务器上的

server {listen       80;listen  [::]:80;#access_log  /var/log/nginx/host.access.log  main;location / {add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';root   /usr/share/nginx/html;index  index.html index.htm;}location /web/ {add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';proxy_pass   http://172.17.0.1:8080/;}location /data/ {add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';proxy_pass   http://172.17.0.1:8080/datahub/;}location /biz/ {add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';proxy_pass   http://172.17.0.1:8080/bizhub/;}location /elastic/ {add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';proxy_pass   http://172.17.0.1:9200/;}location /coding/ {add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';proxy_pass   http://172.17.0.1:8080/geocoding/;}location /bladevisual/ {add_header Access-Control-Allow-Origin *;add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';proxy_pass   http://172.17.0.1:8080/bladevisual/;}}

相关内容

热门资讯

AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWR报告解读 WORKLOAD REPOSITORY PDB report (PDB snapshots) AW...
AWS管理控制台菜单和权限 要在AWS管理控制台中创建菜单和权限,您可以使用AWS Identity and Access Ma...
​ToDesk 远程工具安装及... 目录 前言 ToDesk 优势 ToDesk 下载安装 ToDesk 功能展示 文件传输 设备链接 ...
群晖外网访问终极解决方法:IP... 写在前面的话 受够了群晖的quickconnet的小水管了,急需一个新的解决方法&#x...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
Azure构建流程(Power... 这可能是由于配置错误导致的问题。请检查构建流程任务中的“发布构建制品”步骤,确保正确配置了“Arti...