Nginx Proxy 代理

1、代理原理
  • 反向代理产生的背景:
    在计算机世界里,由于单个服务器的处理客户端(用户)请求能力有一个极限,当用户的接入请求蜂拥而入时,会造成服务器忙不过来的局面,可以使用多个服务器来共同分担成千上万的用户请求,这些服务器提供相同的服务,对于用户来说,根本感觉不到任何差别。
  • 反向代理服务的实现:
    需要有一个负载均衡设备(即反向代理服务器)来分发用户请求,将用户请求分发到空闲的服务器上。服务器返回自己的服务到负载均衡设备。负载均衡设备将服务器的服务返回用户。

Nginx-2 - 图1

Nginx-2 - 图2

2、正/反向代理的区别

什么是反向代理?为什么叫反向代理?什么是正向代理?我们来举例说明

  • 正向代理:
    举例:贷款
    正向代理的过程隐藏了真实的请求客户端,服务器不知道真实的客户端是谁,客户端请求的服务都被代理服务器代替请求。我们常说的代理也就是正向代理,正向代理代理的是请求方,也就是客户端;比如我们要访问youtube,可是不能访问,只能先安装个FQ软件代你去访问,通过FQ软件才
    能访问,FQ软件就叫作正向代理。

Nginx-2 - 图3

反向代理:
反向代理的过程隐藏了真实的服务器,客户不知道真正提供服务的人是谁,客户端请求的服务都被代理服务器处理。反向代理代理的是响应方,也就是服务端;我们请求www.baidu.com时,这www.baidu.com就是反向代理服务器,真实提供服务的服务器有很多台,反向代理服务器会把我们的请求分/转发到真实提供服务的各台服务器。Nginx就是性能非常好的反向代理服务器,用来做负载均衡。

Nginx-2 - 图4

反向代理中,proxy和server同属一个LAN

反向代理中代理的对象是服务端,proxy和server同属一个LAN,对client透明。

Nginx-2 - 图5

正向代理和反向代理对比示意图

正向代理中代理的对象是客户端,proxy和client同属一个LAN,对server透明;

Nginx-2 - 图6

3、知识扩展
  1. HTTP Server(Web服务器)和Application Server(应用服务器)的区别和联系
    Apache/Nginx是静态服务器(HTTP Server):
    Nginx优点:负载均衡、反向代理、处理静态文件优势。nginx处理静态请求的速度高于apache;
    Apache优点:相对于Tomcat服务器来说处理静态文件是它的优势,速度快。Apache是静态解析,适合静态HTML、图片等。
    HTTP Server 关心的是 HTTP 协议层面的传输和访问控制,所以在 Apache/Nginx 上你可以看到代理、负载均衡等功能;
    HTTP Server(Nginx/Apache)常用做静态内容服务和代理服务器,将外来请求转发给后面的应用服务(tomcat,jboss,jetty等)。
    应用服务器(tomcat/jboss/jetty)是动态服务器(Application Server):
    应用服务器Application Server,则是一个应用执行的容器。它首先需要支持开发语言的 Runtime(对于 Tomcat 来说,就是 Java,若是Ruby/Python 等其他语言开发的应用也无法直接运行在 Tomcat 上)。
  2. 但是事无绝对,为了方便,应用服务器(如tomcat)往往也会集成 HTTP Server 的功能,nginx也可以通过模块开发来提供应用功能,只是不如专业的 HTTP Server 那么强大,所以应用服务器往往是运行在 HTTP Server 的背后,执行应用,将动态的内容转化为静态的内容之后,通过 HTTP Server 返回到客户端。
  3. 常用开源集群软件有:lvs,keepalived,haproxy,nginx,apache
    常用商业集群硬件有:F5, Netscaler,Radware,A10等

静态请求:访问的是静态资源(比如..html页面,.jpg图片等等),由Nginx/Apache直接处理即可
动态请求:访问需要与数据库进行交互,需要后端应用服务器来进行处理;

4、nginx Proxy 配置

1、代理模块

  1. ngx_http_proxy_module

2、代理配置

  1. 代理
  2. Syntax: proxy_pass URL; #代理的后端服务器URL
  3. Default: —
  4. Context: location, if in location, limit_except
  5. host: www.qf.com
  6. remote_addr: 10.8.165.79
  7. client-->nginx proxy-->real-server
  8. 头信息
  9. Syntax: proxy_set_header field value;
  10. Default: proxy_set_header Host $proxy_host; #设置真实客户端地址
  11. proxy_set_header Connection close;
  12. Context: http, server, location
  13. 超时
  14. Syntax: proxy_connect_timeout time;
  15. Default: proxy_connect_timeout 60s; #链接超时
  16. Context: http, server, location
  17. Syntax: proxy_read_timeout time;
  18. Default: proxy_read_timeout 60s;
  19. Context: http, server, location
  20. Syntax: proxy_send_timeout time; #nginx进程向fastcgi进程发送request的整个过程的超时时间
  21. Default: proxy_send_timeout 60s;
  22. Context: http, server, location

3、启用 nginx proxy 代理

环境2台nginx真实服务器

a、nginx-1 启动网站(内容)(作为网站服务器)·

  1. nginx-1的ip:192.168.62.157
  2. 已经编译安装好,检查nginx是否启动是否可以访问
  3. [root@nginx-server ~]# cat /home/www/html/index.html
  4. 1000phone
  5. [root@nginx-server ~]# cat /etc/nginx/conf.d/aa.conf
  6. server {
  7. listen 80;
  8. server_name localhost;
  9. location / {
  10. root /home/www/html;
  11. index index.html index.hml;
  12. }
  13. }

b、nginx-2 启动代理程序

  1. nginx-2的ip:192.168.62.159
  2. 配置nginx的yum源直接yum安装
  3. 启动
  4. 编辑nginx的配置文件(编辑之前,删除/注释掉之前的配置):
  5. [root@nginx-server ~]# vim /etc/nginx/conf.d/default.conf
  6. server {
  7. listen 80;
  8. server_name localhost;
  9. location / {
  10. proxy_pass http://192.168.62.157:80;
  11. proxy_set_header Host $http_host;
  12. proxy_set_header X-Real-IP $remote_addr;
  13. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  14. proxy_connect_timeout 30;
  15. proxy_send_timeout 60;
  16. proxy_read_timeout 60;
  17. }
  18. }
  19. 重新加载nginx配置文件
  20. [root@nginx-server ~]# nginx -s reload

c、nginx proxy 具体配置详解

  1. proxy_pass :真实服务器的地址,可以是ip也可以是域名和url地址
  2. proxy_set_header:重新定义或者添加发往后端服务器的请求头
  3. proxy_set_header X-Real-IP :启用客户端真实地址(否则日志中显示的是代理在访问网站)
  4. proxy_set_header X-Forwarded-For:记录代理地址
  5. proxy_connect_timeout:后端服务器连接的超时时间发起三次握手等候响应超时时间
  6. proxy_send_timeout:后端服务器数据回传时间,就是在规定时间之内后端服务器必须传完所有的数据
  7. proxy_read_timeout :nginx接收upstream(上游/真实) server数据超时, 默认60s, 如果连续的60s内没有收到1个字节, 连接关闭。像长连接

Nginx-2 - 图7

  1. proxy_set_header X-Real-IP
  2. 未配置
  3. Nginxbackend 的日志:记录只有192.168.107.112
  4. 配置
  5. Nginxbackend 的日志,记录的有192.168.162.16 192.168.107.107 192.168.107.112

注意:proxy_pass http:// 填写nginx-1服务器的地址。

d、 使用PC客户端访问nginx-2服务器地址
浏览器中输入http://192.168.62.159/ (也可以是nginx-2服务器的域名)

成功访问nginx-1服务器页面
e、 观察nginx-1(192.168.62.157)服务器的日志

Nginx-2 - 图8192.168.62.159 代理服务器地址

192.168.62.1 客户端地址

访问成功。 记录了客户端的IP和代理服务器的IP

5、Nginx负载均衡

1、负载均衡的作用

如果你的Nginx服务器给2台web服务器做代理,负载均衡算法采用轮询,那么当你的一台机器web程序关闭造成web不能访问,那么Nginx服务器分发请求还是会给这台不能访问的web服务器,如果这里的响应连接时间过长,就会导致客户端的页面一直在等待响应,对用户来说体验就大大折扣,这里我们怎么避免这样的情况发生呢。这里我配张图来说明下问题。

Nginx-2 - 图9

如果负载均衡中其中web2发生这样的情况,Nginx首先会去web1请求,但是Nginx在配置不当的情况下会继续分发请求到web2,然后等待web2响应,直到我们的响应时间超时,才会把请求重新分发给web1,这里的响应时间如果过长,用户等待的时间就会越长。

2、upstream配置

首先给大家说下 upstream 这个配置的,这个配置是写一组被代理的服务器地址,然后配置负载均衡的算法。这里的被代理服务器地址有2种写法。
代理服务器的配置:

  1. upstream youngfitapp {
  2. server 192.168.62.157:8080;
  3. server 192.168.62.158:8080;
  4. }
  5. server {
  6. listen 80;
  7. server_name localhost;
  8. location / {
  9. proxy_pass http://youngfitapp;
  10. proxy_set_header Host $http_host;
  11. proxy_set_header X-Real-IP $remote_addr;
  12. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  13. }
  14. }

3、负载均衡算法(分发策略)

upstream 支持4种负载均衡调度算法:

A、轮询(默认):每个请求按时间顺序逐一分配到不同的后端服务器;

B、ip_hash:每个请求按访问IP的hash结果分配,同一个IP客户端固定访问一个后端服务器。可以保证来自同一ip的请求被打到固定的机器上,可以解决session问题;

C、url_hash:按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器。后台服务器为缓存的时候效率;

D、fair:这是比上面两个更加智能的负载均衡算法。此种算法可以依据页面大小和加载时间长短智能地进行负载均衡,也就是根据后端服务器的响应时间来分配请求,响应时间短的优先分配。Nginx本身是不支持 fair的,如果需要使用这种调度算法,必须下载Nginx的 upstream_fair模块;

3、配置实例

1、热备:如果你有2台后端服务器,当一台服务器发生事故时,才启用第二台服务器给提供服务。服务器处理请求的顺序:AAAAAA突然A挂啦,BBBBBBBBBBBBBB…..

  1. upstream myweb {
  2. server 192.168.62.157:8080;
  3. server 192.168.62.158:8080 backup; #热备
  4. }

2、轮询:Nginx默认就是轮询其权重都默认为1,服务器处理请求的顺序:ABABABABAB….

  1. upstream myweb {
  2. server 192.168.62.157:8080;
  3. server 192.168.62.158:8080;
  4. }

3、加权轮询:根据配置的权重的大小而分发给不同服务器不同数量的请求。如果不设置,则默认为1。下面服务器的请求顺序为:ABBABBABBABBABB….

  1. upstream myweb {
  2. server 192.168.62.157:8080 weight=1;
  3. server 192.168.62.158:8080 weight=2;
  4. }

4、ip_hash:Nginx会让相同的客户端ip请求相同的服务器。

  1. upstream myweb {
  2. ip_hash;
  3. server 192.168.62.157:8080;
  4. server 192.168.62.158:8080;
  5. }

5、nginx负载均衡配置状态参数

  • down,表示当前的server暂时不参与负载均衡。
  • backup,预留的备份机器。当其他所有的非backup机器出现故障或者忙的时候,才会请求backup机器,因此这台机器的压力最轻。
  • max_fails,允许请求失败的最大次数,默认为1。当超过最大次数时,返回错误。
  • fail_timeout,在经历了max_fails次失败后,暂停服务的时间单位秒。max_fails可以和fail_timeout一起使用。
  1. upstream myweb {
  2. server 192.168.62.157:8080 weight=2 max_fails=2 fail_timeout=2;
  3. server 192.168.62.158:8080 weight=1 max_fails=2 fail_timeout=1;
  4. }

如果想更多更深入的了解 nginx 的负载均衡算法,nginx官方提供一些插件大家可以了解下。

4、nginx配置7层协议及4层协议方法(扩展)

举例讲解下什么是7层协议,什么是4层协议。

(1)7层协议

OSI(Open System Interconnection)是一个开放性的通行系统互连参考模型,他是一个定义的非常好的协议规范,共包含七层协议。直接上图,这样更直观些:

Nginx-2 - 图10

(2)4层协议

TCP/IP协议
之所以说TCP/IP是一个协议族,是因为TCP/IP协议包括TCP、IP、UDP、ICMP、RIP、TELNETFTP、SMTP、ARP、TFTP等许多协议,这些协议一起称为TCP/IP协议。

从协议分层模型方面来讲,TCP/IP由四个层次组成:网络接口层、网络层、传输层、应用层。

Nginx-2 - 图11

(3)协议配置

这里我们举例,在nginx做负载均衡,负载多个服务,部分服务是需要7层的,部分服务是需要4层的,也就是说7层和4层配置在同一个配置文件中。

准备三台机器:

代理服务IP:10.0.105.201 —配置本地host解析域名;

后端服务器IP:nginx-a :10.0.105.199/nginx-b:10.0.105.202(yum安装)后端服务器将nginx服务启动

配置代理服务器的nginx配置文件

  1. worker_processes 4;
  2. worker_rlimit_nofile 102400;
  3. events {
  4. worker_connections 1024;
  5. }
  6. http {
  7. include mime.types;
  8. default_type application/octet-stream;
  9. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  10. '$status $body_bytes_sent "$http_referer" '
  11. '"$http_user_agent" "$http_x_forwarded_for"';
  12. #access_log logs/access.log main;
  13. sendfile on;
  14. keepalive_timeout 65;
  15. gzip on;
  16. upstream testweb {
  17. ip_hash;
  18. server 10.0.105.199:80 weight=2 max_fails=2 fail_timeout=2s;
  19. server 10.0.105.202:80 weight=2 max_fails=2 fail_timeout=2s;
  20. }
  21. server {
  22. listen 80;
  23. server_name www.test.com;
  24. charset utf-8;
  25. #access_log logs/host.access.log main;
  26. location / {
  27. proxy_pass http://testweb;
  28. proxy_set_header Host $host:$server_port;
  29. proxy_set_header X-Real-IP $remote_addr;
  30. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  31. }
  32. error_page 500 502 503 504 /50x.html;
  33. location = /50x.html {
  34. root html;
  35. }
  36. }
  37. }
  38. }

浏览器测试访问:

http://www.test.com/

10.0.105.202 10.0.105.199服务器yum安装的创建新的配置文件:

  1. [root@nginx-server ~]# cd /etc/nginx/conf.d/
  2. [root@nginx-server conf.d]# cp default.conf test.conf
  3. [root@nginx-server conf.d]# cat test.conf
  4. server {
  5. listen 80;
  6. server_name localhost;
  7. location / {
  8. root /usr/share/nginx/html;
  9. index index.html index.htm;
  10. }
  11. }
  12. [root@nginx-server ~]# nginx -s reload

nginx在1.9.0的时候,增加了一个 stream 模块,用来实现四层协议(网络层和传输层)的转发、代理、负载均衡等。stream模块的用法跟http的用法类似,允许我们配置一组TCP或者UDP等协议的监听,然后通过proxy_pass来转发我们的请求,通过upstream添加多个后端服务,实现负载均衡。

  1. #4层tcp负载
  2. stream {
  3. upstream myweb {
  4. hash $remote_addr consistent;
  5. server 172.17.14.2:8080;
  6. server 172.17.14.3:8080;
  7. }
  8. server {
  9. listen 80;
  10. proxy_connect_timeout 10s;
  11. proxy_timeout 30s;
  12. proxy_pass myweb;
  13. }
  14. }

Nginx 会话保持

nginx会话保持主要有以下几种实现方式。

1、ip_hash

ip_hash使用源地址哈希算法,将同一客户端的请求总是发往同一个后端服务器,除非该服务器不可用。
ip_hash语法:

  1. upstream backend {
  2. ip_hash;
  3. server backend1.example.com;
  4. server backend2.example.com;
  5. server backend3.example.com down;
  6. }

ip_hash简单易用,但有如下问题:
当后端服务器宕机后,session会话丢失;
同一客户端会被转发到同一个后端服务器,可能导致负载失衡;

2、sticky_cookie_insert

使用sticky_cookie_insert启用会话亲缘关系,这会导致来自同一客户端的请求被传递到一组服务器的同一台服务器。与ip_hash不同之处在于,它不是基于IP来判断客户端的,而是基于cookie来判断。因此可以避免上述ip_hash中来自同一客户端导致负载失衡的情况。(需要引入第三方模块才能实现)
sticky模块
语法:

  1. upstream backend {
  2. server backend1.example.com;
  3. server backend2.example.com;
  4. sticky_cookie_insert srv_id expires=1h domain=www.youngfit.cn path=/;
  5. }
  6. server {
  7. listen 80;
  8. server_name www.youngfit.cn;
  9. location / {
  10. proxy_pass http://backend;
  11. }
  12. }

说明:
expires:设置浏览器中保持cookie的时间
domain:定义cookie的域
path:为cookie定义路径

3. jvm_route

jvm_route的原理

  1. 一开始请求过来,没有带session信息,jvm_route就根据轮询(round robin)的方法,发到一台tomcat上面。
  2. tomcat添加上session 信息,并返回给客户。
  3. 用户再次请求,jvm_route看到session中有后端服务器的名称,它就把请求转到对应的服务器上。

Nginx 实现动静分离

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

1、准备环境

  1. 192.168.62.159 代理服务器
  2. 192.168.62.157 动态资源
  3. 192.168.62.155 静态资源

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

  1. 192.168.62.159 代理服务器
  2. 1.配置nginx反向代理upstream;
  3. [root@nginx-server conf.d]# cat upstream.conf
  4. upstream static {
  5. server 192.168.62.155:80 weight=1 max_fails=1 fail_timeout=60s;
  6. }
  7. upstream phpserver {
  8. server 192.168.62.157:80 weight=1 max_fails=1 fail_timeout=60s;
  9. }
  10. server {
  11. listen 80;
  12. server_name localhost;
  13. #动态资源加载
  14. location ~ \.(php|jsp)$ {
  15. proxy_pass http://phpserver;
  16. proxy_set_header Host $host:$server_port;
  17. proxy_set_header X-Real-IP $remote_addr;
  18. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  19. }
  20. #静态资源加载
  21. location ~ .*\.(html|gif|jpg|png|bmp|swf|css|js)$ {
  22. proxy_pass http://static;
  23. proxy_set_header Host $host:$server_port;
  24. proxy_set_header X-Real-IP $remote_addr;
  25. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  26. }
  27. }
  1. 192.168.62.155 静态资源
  2. #静态资源配置 主配置文件-include /etc/nginx/conf.d/*.conf
  3. # vim /etc/nginx/conf.d/static.conf
  4. server {
  5. listen 80;
  6. server_name localhost;
  7. location ~ \.(html|jpg|png|js|css|gif|bmp|jpeg) {
  8. root /home/www/nginx;
  9. index index.html index.htm;
  10. }
  11. }
  12. [root@nginx-server2 nginx]# cat /home/www/nginx/index.html //模拟静态资源
  13. hello 155
  1. 192.168.62.157 动态资源
  2. #动态资源配置:
  3. yum 安装php7.1
  4. [root@nginx-server ~]# rpm -Uvh https://mirror.webtatic.com/yum/el7/epel-release.rpm
  5. [root@nginx-server ~]# rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
  6. [root@nginx-server ~]# yum install php71w-xsl php71w php71w-ldap php71w-cli php71w-common php71w-devel php71w-gd php71w-pdo php71w-mysql php71w-mbstring php71w-bcmath php71w-mcrypt -y
  7. [root@nginx-server ~]# yum install -y php71w-fpm
  8. [root@nginx-server ~]# systemctl start php-fpm
  9. [root@nginx-server ~]# systemctl enable php-fpm
  10. 编辑nginx的配置文件:
  11. server {
  12. listen 80;
  13. server_name localhost;
  14. location ~ \.php$ {
  15. root /home/nginx/html; #指定网站目录
  16. fastcgi_pass 127.0.0.1:9000; #指定访问地址
  17. fastcgi_index index.php; #指定默认文件
  18. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #站点根目录,取决于root配置项
  19. include fastcgi_params; #包含nginx常量定义
  20. }
  21. }
  22. [root@nginx-server1 html]# cat /home/nginx/html/index.php //模拟动态资源
  23. dongtai
  24. 或者替换为php代码:
  25. <?php
  26. phpinfo();
  27. ?>

当访问静态页面的时候location 匹配到 (html|jpg|png|js|css|gif|bmp|jpeg) 通过转发到静态服务器,静态服务通过location的正则匹配来处理请求。

当访问动态页面时location匹配到 .\php 结尾的文件转发到后端php服务处理请求。

Nginx-2 - 图13

Nginx-2 - 图14

Nginx 防盗链问题
  1. 两个网站 A 和 B, B网站引用了A网站上的图片,这种行为就叫做盗链。
  2. 防盗链,就是要防止B引用A的图片。

1、Nginx 防止网站资源被盗用模块
  1. ngx_http_referer_module

如何区分哪些是不正常的用户?

  1. HTTP Referer是Header的一部分,当浏览器向Web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器借此可以获得一些信息用于处理,例如防止未经允许的网站盗链图片、文件等。因此HTTP Referer头信息是可以通过程序来伪装生成的,所以通过Referer信息防盗链并非100%可靠,但是,它能够限制大部分的盗链情况。

2. 防盗链配置

配置要点:

  1. [root@nginx-server ~]# vim /etc/nginx/nginx.conf
  2. # 日志格式添加"$http_referer"
  3. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  4. '$status $body_bytes_sent "$http_referer" '
  5. '"$http_user_agent" "$http_x_forwarded_for"';
  6. # valid_referers 使用方式
  7. Syntax: valid_referers none | blocked | server_names | string ...;
  8. Default: —
  9. Context: server, location
  • none : 允许没有http_referer的请求访问资源;
  • blocked : 允许不是http://开头的,不带协议的请求访问资源---被防火墙过滤掉的;
  • server_names : 只允许指定ip/域名来的请求访问资源(白名单);
    准备两台机器,一张图片网站服务器;
    1. 图片网站服务器:上传图片192.168.1.9
    2. [root@nginx-server ~]# cp test.jpg /usr/share/nginx/html/
    3. [root@nginx-server ~]# cd /etc/nginx/conf.d/
    4. [root@nginx-server conf.d]# cp default.conf default.conf.bak
    5. [root@nginx-server conf.d]# mv default.conf nginx.conf
    6. [root@nginx-server conf.d]# vim nginx.conf
    7. server {
    8. listen 80;
    9. server_name localhost;
    10. location / {
    11. root /usr/share/nginx/html;
    12. index index.html index.htm;
    13. }
    14. }
    15. [root@nginx-server conf.d]# nginx -t
    16. [root@nginx-server conf.d]# systemctl restart nginx

    访问:
    Nginx-2 - 图15
    Nginx-2 - 图16
    Referer:这个匹配的值为空 “-” ```shell 盗链机器配置:192.168.1.10 [root@nginx-client html]# cat /etc/nginx/conf.d/qf.conf server {
    1. listen 80;
    2. server_name localhost;
    3. location / {
    4. root /usr/share/nginx/html;
    5. index index.html;
    6. }
    }

[root@nginx-client ~]# cd /usr/share/nginx/html/ [root@nginx-client html]# cp index.html index.html.bak [root@nginx-client html]# vim index.html

Nginx-2 - 图17 [root@nginx-client html]# systemctl restart nginx

  1. <br />![](https://youngfitfei.oss-cn-beijing.aliyuncs.com/img/1583393072658.png#crop=0&crop=0&crop=1&crop=1&id=a6GNC&originHeight=478&originWidth=481&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)<br />查看图片网站服务器日志:<br />![](https://youngfitfei.oss-cn-beijing.aliyuncs.com/img/1583393094531.png#crop=0&crop=0&crop=1&crop=1&height=30&id=Ry9JB&originHeight=19&originWidth=479&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=&width=756)<br />Referer记录了:连接是1.10这台机器。
  2. ```shell
  3. 防盗链配置
  4. 在图片服务器操作
  5. [root@nginx-server conf.d]# vim nginx.conf
  6. server {
  7. listen 80;
  8. server_name localhost;
  9. location / {
  10. root /usr/share/nginx/html;
  11. index index.html index.htm;
  12. valid_referers none blocked www.jd.com; #允许这些访问
  13. if ($invalid_referer) {
  14. return 403;
  15. }
  16. }
  17. }
  18. [root@nginx-server conf.d]# systemctl restart nginx


测试访问:
Nginx-2 - 图18
图片服务器查看日志:
Nginx-2 - 图19
上面配置并没有允许192.168.1.10这台机器访问。

  1. 实例二,继续在图片服务器上面操作
  2. [root@nginx-server html]# vim /etc/nginx/conf.d/nginx.conf #将原来的删除掉
  3. server {
  4. listen 80;
  5. server_name localhost;
  6. location ~ .*\.(gif|jpg|png|jpeg)$ {
  7. root /usr/share/nginx/html;
  8. valid_referers none blocked *.qf.com 192.168.1.10;
  9. if ($invalid_referer) {
  10. return 403;
  11. }
  12. }
  13. }
  14. 因为none允许为空值访问,所以加不加ip都可以访问,如果把none擦除,就不可以了
  15. 重载nginx服务
  16. [root@nginx-server ~]# nginx -s reload
  1. 在其中一台机器测试:
  2. 测试不带http_refer:
  3. [root@nginx-server conf.d]# curl -I "http://192.168.1.9/test.jpg"
  4. HTTP/1.1 200 OK
  5. Server: nginx/1.16.1
  6. Date: Mon, 02 Sep 2019 14:02:56 GMT
  7. Content-Type: image/jpeg
  8. Content-Length: 27961
  9. Last-Modified: Mon, 02 Sep 2019 13:23:12 GMT
  10. Connection: keep-alive
  11. ETag: "5d6d17c0-6d39"
  12. Accept-Ranges: bytes
  13. 测试带非法http_refer:
  14. [root@nginx-server conf.d]# curl -e http://www.baidu.com -I "http://192.168.1.9/test.jpg"
  15. HTTP/1.1 403 Forbidden
  16. Server: nginx/1.16.1
  17. Date: Mon, 02 Sep 2019 14:03:48 GMT
  18. Content-Type: text/html
  19. Content-Length: 153
  20. Connection: keep-alive
  21. 测试带合法的http_refer:
  22. [root@nginx-server conf.d]# curl -e http://www.qf.com -I "http://192.168.1.9/test.jpg"
  23. HTTP/1.1 200 OK
  24. Server: nginx/1.16.1
  25. Date: Mon, 02 Sep 2019 14:04:52 GMT
  26. Content-Type: image/jpeg
  27. Content-Length: 27961
  28. Last-Modified: Mon, 02 Sep 2019 13:23:12 GMT
  29. Connection: keep-alive
  30. ETag: "5d6d17c0-6d39"
  31. Accept-Ranges: bytes
  32. [root@ansible-server conf.d]# curl -e http://192.168.1.10 -I "http://192.168.1.9/test.jpg"
  33. HTTP/1.1 200 OK
  34. Server: nginx/1.16.1
  35. Date: Mon, 02 Sep 2019 14:05:36 GMT
  36. Content-Type: image/jpeg
  37. Content-Length: 27961
  38. Last-Modified: Mon, 02 Sep 2019 13:23:12 GMT
  39. Connection: keep-alive
  40. ETag: "5d6d17c0-6d39"
  41. Accept-Ranges: bytes


如果用户直接在浏览器输入你的图片地址,那么图片显示正常,因为它符合规则。
在图片服务器查看日志:
Nginx-2 - 图20

Nginx rewrite地址重写

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

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

2.1、if 语句
  • 应用环境
    1. server,location

    语法:
    rewrite 指令根据表达式来重定向URI,或者修改字符串。可以应用于server,location, if环境下每行rewrite指令最后跟一个flag标记,支持的flag标记有:
    www.qf.com —> www.jd.com
    redirect 和 permanent区别则是返回的不同方式的重定向,对于客户端来说一般状态下是没有区别的。而对于搜索引擎,相对来说301的重定向更加友好,如果我们把一个地址采用301跳转方式跳转的话,搜索引擎会把老地址的相关信息带到新地址,同时在搜索引擎索引库中彻底废弃掉原先的老地址。使用302重定向时,搜索引擎(特别是google)有时会查看跳转前后哪个网址更直观,然后决定显示哪个,如果它觉的跳转前的URL更好的话,也许地址栏不会更改。
    2.2、Rewrite flag

2.3、Rewrite匹配参考示例
  1. 本地解析hosts文件(windows)
  2. 192.168.62.153 www.testpm.com
  3. 例1:
  4. [root@nginx html]# pwd
  5. /html
  6. [root@nginx html]# ls
  7. a b
  8. [root@nginx html]# cat a/1.html
  9. 1.html
  10. [root@nginx html]# cat b/2.html
  11. 22
  12. # http://www.testpm.com/a/1.html ==> http://www.testpm.com/b/2.html
  13. server {
  14. listen 80;
  15. server_name www.testpm.com;
  16. location /a {
  17. root /html;
  18. index 1.html index.htm;
  19. rewrite .* /b/2.html permanent;
  20. }
  21. location /b {
  22. root /html;
  23. index 2.html index.htm;
  24. }
  25. }
  26. 例2:
  27. [root@mycat html]# pwd
  28. /var/www/html
  29. [root@mycat html]# ls
  30. 2018 2019
  31. [root@mycat html]# cat 2018/a/1.html
  32. 2018
  33. [root@mycat html]# cat 2019/a/1.html
  34. 2019
  35. # http://www.testpm.com/2019/a/1.html ==> http://www.testpm.com/2018/a/1.html
  36. server {
  37. listen 80;
  38. server_name www.testpm.com;
  39. location /2019/a {
  40. root /var/www/html;
  41. index 1.html index.hml;
  42. rewrite ^/2019/(.*)$ /2018/$1 permanent;
  43. }
  44. location /2018/a {
  45. root /var/www/html;
  46. index 1.html index.htl;
  47. }
  48. }
  49. 例3:
  50. # http://www.qf.com/a/1.html ==> http://jd.com
  51. location /a {
  52. root /html;
  53. if ($host ~* qf.com) {
  54. rewrite .* http://jd.com permanent;
  55. }
  56. }
  57. 例4:
  58. # http://www.youngfit.com/a/1.html ==> http://jd.com/a/1.html
  59. location /a {
  60. root /html;
  61. if ( $host ~* youngfit.com ){
  62. rewrite .* http://jd.com$request_uri permanent;
  63. }
  64. }
  65. 例5: 在访问目录后添加/ (如果目录后已有/,则不加/)
  66. [root@nginx-server c]# pwd
  67. /usr/share/nginx/html/a/b/c
  68. http://www.qf.com/a/b/c--->http://www.qf.com/a/b/c/
  69. # http://www.qf.com/a/b/c
  70. # $1: /a/b/
  71. # $2: c
  72. # http://$host$1$2/
  73. location /a/b/c {
  74. root /usr/share/nginx/html;
  75. index index.html index.hml;
  76. if (-d $request_filename) {
  77. rewrite ^(.*)([^/])$ http://$host$1$2/ permanent;
  78. }
  79. }
  80. 例6:
  81. [root@nginx html]# pwd
  82. /usr/share/nginx/html
  83. [root@nginx html]# ls
  84. 50x.html index.html index.html.bak1 reg
  85. [root@nginx html]# cat reg/login.html
  86. login
  87. # http://www.qf.com/login/qf.html ==> http://www.qf.com/reg/login.html?user=qf
  88. location /login {
  89. root /usr/share/nginx/html;
  90. rewrite ^/login/(.*)\.html$ http://$host/reg/login.html?user=$1;
  91. #或者: rewrite ^/login/(.*)\.html$ /reg/login.html?user=$1;
  92. }
  93. location /reg {
  94. root /usr/share/nginx/html;
  95. index login.html;
  96. }
  97. 例7:
  98. [root@nginx-server 33]# pwd
  99. /html/qf/11/22/33
  100. [root@nginx-server 33]# cat 1.html
  101. hello nginx
  102. #http://www.qf.com/qf/11-22-33/1.html ==> http://www.qf.com/qf/11/22/33/1.html
  103. location /qf {
  104. rewrite ^/qf/([0-9]+)-([0-9]+)-([0-9]+)(.*)$ /qf/$1/$2/$3$4 permanent;
  105. }
  106. location /qf/11/22/33 {
  107. root /html;
  108. index 1.html;
  109. }

2.4、set 指令

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

  1. server,location,if

应用示例

  1. 例8:
  2. #http://alice.testpm.com ==> http://www.testpm.com/alice
  3. #http://jack.testpm.com ==> http://www.testpm.com/jack
  4. #http://kobe.testpm.com ==> http://www.testpm.com/kobe
  5. [root@nginx-server conf.d]# cd /usr/share/nginx/html/
  6. [root@nginx-server html]# mkdir jack alice
  7. [root@nginx-server html]# echo "jack.." >> jack/index.html
  8. [root@nginx-server html]# echo "alice.." >> alice/index.html
  9. windows本地解析域名host文件
  10. 192.168.62.153 www.testpm.com
  11. 192.168.62.153 alice.testpm.com
  12. 192.168.62.153 jack.testpm.com
  13. 编辑配置文件:
  14. server {
  15. listen 80;
  16. server_name www.testpm.com;
  17. location / {
  18. root /usr/share/nginx/html;
  19. index index.html index.htm;
  20. # http://www.testpm.com
  21. if ( $host ~* ^www.testpm.com$) {
  22. break;
  23. }
  24. # http://jack.testpm.com --> http://www.testpm.com/jack
  25. if ( $host ~* "^(.*)\.testpm\.com$" ) {
  26. set $user $1;
  27. rewrite .* http://www.testpm.com/$user permanent;
  28. }
  29. }
  30. location /jack {
  31. root /usr/share/nginx/html;
  32. index index.html index.hml;
  33. }
  34. location /alice {
  35. root /usr/share/nginx/html;
  36. index index.html index.hml;
  37. }
  38. }

2.5、return 指令

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

  1. server,location,if

应用示例:

  1. 例9:如果访问的.sh结尾的文件则返回403操作拒绝错误
  2. http://www.testpm.com/1.sh 返回403
  3. server {
  4. listen 80;
  5. server_name www.testpm.com;
  6. #access_log /var/log/nginx/http_access.log main;
  7. location / {
  8. root /usr/share/nginx/html;
  9. index index.html index.htm;
  10. }
  11. location ~* \.sh$ {
  12. return 403;
  13. }
  14. }
  15. 例10:80 ======> 443:80转443端口
  16. server {
  17. listen 80;
  18. server_name www.testpm.cn;
  19. access_log /var/log/nginx/http_access.log main;
  20. return 301 https://www.testpm.cn$request_uri;
  21. }
  22. server {
  23. listen 443 ssl;
  24. server_name www.testpm.cn;
  25. access_log /var/log/nginx/https_access.log main;
  26. #ssl on;
  27. ssl_certificate /etc/nginx/cert/2447549_www.testpm.cn.pem;
  28. ssl_certificate_key /etc/nginx/cert/2447549_www.testpm.cn.key;
  29. ssl_session_timeout 5m;
  30. ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  31. ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
  32. ssl_prefer_server_ciphers on;
  33. location / {
  34. root /usr/share/nginx/html;
  35. index index.html index.htm;
  36. }
  37. }
  38. [root@nginx-server ~]# curl -I http://www.testpm.cn
  39. HTTP/1.1 301 Moved Permanently
  40. Server: nginx/1.16.0
  41. Date: Wed, 03 Jul 2019 13:52:30 GMT
  42. Content-Type: text/html
  43. Content-Length: 169
  44. Connection: keep-alive
  45. Location: https://www.testpm.cn/

3、last,break详解

Nginx-2 - 图21

  1. [root@localhost test]# cat /etc/nginx/conf.d/last_break.conf
  2. server {
  3. listen 80;
  4. server_name localhost;
  5. location / {
  6. root /usr/share/nginx/html;
  7. index index.html index.htm;
  8. }
  9. #192.168.153.147/break --> 192.168.153.147/test/break.html
  10. location /break/ {
  11. root /usr/share/nginx/html;
  12. rewrite .* /test/break.html break;
  13. }
  14. #192.168.153.147/last --> 192.168.153.147/test/last.html
  15. #192.168.153.147/test/last.html --> 192.168.153.147/test/test.html
  16. location /last/ {
  17. root /usr/share/nginx/html;
  18. rewrite .* /test/last.html last;
  19. }
  20. location /test/ {
  21. root /usr/share/nginx/html;
  22. rewrite .* /test/test.html break;
  23. }
  24. }
  25. [root@localhost conf.d]# cd /usr/share/nginx/html/
  26. [root@localhost html]# mkdir test
  27. [root@localhost html]# echo "last" > test/last.html
  28. [root@localhost html]# echo "break" > test/break.html
  29. [root@localhost html]# echo "test" > test/test.html
  30. http://192.168.62.159/break/
  31. http://192.168.62.159/last/

Nginx-2 - 图22

Nginx-2 - 图23

注意:

  • last 标记在本条 rewrite 规则执行完后,会对其所在的 server { … } 标签重新发起请求;
  • break 标记则在本条规则匹配完成后,停止匹配,不再做后续的匹配;
    4.Nginx 的 https ( rewrite )

    1. server {
    2. listen 80;
    3. server_name *.vip9999.top vip9999.top;
    4. if ($host ~* "^www.vip9999.top$|^vip9999.top$" ) {
    5. return 301 https://www.vip9999.top$request_uri;
    6. }
    7. if ($host ~* "^(.*).vip9999.top$" ) {
    8. set $user $1;
    9. return 301 https://www.vip9999.top/$user;
    10. }
    11. }
    12. # Settings for a TLS enabled server.
    13. server {
    14. listen 443 ssl;
    15. server_name www.vip9999.top;
    16. location / {
    17. root /usr/share/nginx/html;
    18. index index.php index.html;
    19. }
    20. #pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    21. location ~ \.php$ {
    22. root /usr/share/nginx/html;
    23. fastcgi_pass 127.0.0.1:9000;
    24. fastcgi_index index.php;
    25. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    26. include fastcgi_params;
    27. }
    28. ssl on;
    29. ssl_certificate cert/214025315060640.pem;
    30. ssl_certificate_key cert/214025315060640.key;
    31. ssl_session_cache shared:SSL:1m;
    32. ssl_session_timeout 10m;
    33. ssl_ciphers HIGH:!aNULL:!MD5;
    34. ssl_prefer_server_ciphers on;
    35. }


    Nginx-2 - 图24
    nginx的location指令详解

    5、Apache 的 https ( rewrite )拓展

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

  1. http { # 这个是协议级别
  2.   include mime.types;
  3.   default_type application/octet-stream;
  4.   keepalive_timeout 65;
  5.   gzip on;
  6.     server { # 这个是服务级别
  7.       listen 80;
  8.       server_name localhost;
  9.         location / { # 这个是请求级别
  10.           root html;
  11.           index index.html index.htm;
  12.         }
  13.       }
  14. }

1、location 区段
  • location 是在 server 块中配置,根据不同的URl使用不同的配置,来处理不同的请求。
  • location 是有顺序的,会被第一个匹配的location 处理。
  • 基本语法如下:
    1. location [=|~|~*|^~|@] pattern{……}

    本地解析域名host
    1、没有修饰符 表示:必须以指定模式开始
    2、=表示:必须与指定的模式精确匹配
    2、location 前缀含义
    1. = 表示精确匹配,优先级也是最高的
    2. ^~ 表示url以某个常规字符串开头,理解为匹配url路径即可
    3. ~ 表示区分大小写的正则匹配
    4. ~* 表示不区分大小写的正则匹配
    5. !~ 表示区分大小写不匹配的正则
    6. !~* 表示不区分大小写不匹配的正则
    7. / 通用匹配,任何请求都会匹配到
    8. #优先级
    9. = > ~|~*|!~|!~* > /
    3、location 配置示例
    本地解析域名host
    1、没有修饰符 表示:必须以指定模式开始 ```shell [root@nginx-server nginx]# pwd /home/www/nginx [root@nginx-server nginx]# cat abc/2.html 2.html

server { listen 80; server_name www.qf.com;

  1. location /abc {
  2. root /home/www/nginx;
  3. index 2.html;
  4. }

} 那么,如下是对的: http://www.qf.com/abc

  1. 2、=表示:必须与指定的模式精确匹配
  2. ```shell
  3. server {
  4. listen 80;
  5. server_name www.testpm.cn;
  6. access_log /var/log/nginx/http_access.log main;
  7. location / {
  8. root /usr/share/nginx/html;
  9. index a.html index.htm;
  10. }
  11. location = / {
  12. root /usr/share/nginx/html;
  13. index b.html index.htm;
  14. }
  15. }

进行测试:
http://www.testpm.cn
http://www.testpm.cn/a.html
3、~ 表示:指定的正则表达式要区分大小写

  1. [root@nginx-server nginx]# pwd
  2. /home/www/nginx
  3. [root@nginx-server nginx]# ls
  4. abc ABC
  5. [root@nginx-server nginx]# cat abc/2.html
  6. abc
  7. [root@nginx-server nginx]# cat ABC/2.html
  8. ABC
  9. server {
  10. server_name localhost;
  11. location ~ /abc {
  12. root /home/www/nginx;
  13. index 2.html index.html;
  14. }
  15. }
  16. 那么:
  17. http://192.168.62.153/abc/ #能看到abc
  18. http://192.168.62.153/ABC/ #看不到 404

4、~* 表示:指定的正则表达式不区分大小写

  1. [root@nginx-server nginx]# pwd
  2. /home/www/nginx
  3. [root@nginx-server nginx]# ls
  4. abc ABC
  5. [root@nginx-server nginx]# cat abc/2.html
  6. abc
  7. [root@nginx-server nginx]# cat ABC/2.html
  8. ABC
  9. server {
  10. server_name localhost;
  11. location ~* /abc {
  12. root /home/www/nginx;
  13. index 2.html index.html;
  14. }
  15. }
  16. 那么:
  17. http://192.168.62.153/ABC/

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

查找顺序和优先级

  1. = 大于 ^~ 大于 ~|~*|!~|!~* 大于 /
  2. 多个location配置的情况下匹配顺序为:首先匹配 =,其次匹配^~, 其次是按正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求。
  3. ================================================
  4. (1) =:表示完全匹配;
  5. (2) ^~:匹配URI的前缀,如果一个URI同时满足两个规则的话,匹配最长的规则;
  6. (3) ~:匹配正则表达式,大小写敏感;
  7. (4) ~*:匹配正则表达式,大小写不敏感;
  8. 优先级:(1)> (2) > (3) = (4)
  1. location 区段匹配示例
  2. location = / {
  3.   # 只匹配 / 的查询.
  4.   [ configuration A ]
  5. }
  6. location / {
  7.   # 匹配任何以 / 开始的查询,但是正则表达式与一些较长的字符串将被首先匹配。
  8.   [ configuration B ]
  9. }
  10. location ^~ /images/ {
  11.   # 匹配任何以 /images/ 开始的查询并且停止搜索,不检查正则表达式。
  12.   [ configuration C ]
  13. }
  14. location ~* \.(gif|jpg|jpeg)$ {
  15.   # 匹配任何以gif, jpg, or jpeg结尾的文件,但是所有 /images/ 目录的请求将在Configuration C中处理。
  16.   [ configuration D ]
  17. }
  18. 各请求的处理如下例:
  19. / → configuration A
  20. /documents/document.html → configuration B
  21. /images/1.gif → configuration C
  22. /documents/1.jpg → configuration D

4、root 、alias 指令区别

  1. location /img {
  2. alias /var/www/image;
  3. index index.html;
  4. }
  5. http://192.168.153.231/img ---> /var/www/image/index.html
  6. #若按照上述配置的话,则访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件
  7. location /img {
  8. root /var/www/image;
  9. index index.html;
  10. }
  11. #若按照这种配置的话,则访问/img/目录下的文件时,nginx会去/var/www/image/img/目录下找文件。
  12. http://192.168.153.231/img ---> /var/www/image/img/index.html
  • alias 是一个目录别名的定义;
  • root 则是最上层目录的定义。