nginx rewrite url重写, if,负载均衡 ,nginx反向代理配置

rewrite (url 重写)

语法:rewrite regex replacement flag;,如:
rewrite ^/images/(.*.jpg)$ /imgs/$1 break;

此处的$1用于引用(.*.jpg)匹配到的内容,又如:
rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

示例:
在nginx网页访问目录下创建一个目录,在里面放入一张图片

[root@localhost imgs]# pwd
/usr/local/nginx/html/imgs
[root@localhost imgs]# ls
xxbb.jpg

在网页上访问
image

将原图片存放位置修改名字

[root@localhost html]# mv imgs images
[root@localhost html]# ls
50x.html  images  index.html

发现页面404报错
image

将rewrite机制写入配置文件中

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
        location /imgs {
            rewrite ^/imgs/(.*.jpg)$ /images/$1 break;
        }

//测试一下配置文件语法有无问题
[root@localhost html]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

// 重载配置文件
[root@localhost html]# nginx -s reload

又能访问到页面的图片了
image

示例2:

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
        location /imgs {
            rewrite ^/imgs/(.*.jpg)$ http://www.baidu.com break;
        }

[root@localhost html]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost html]# nginx -s reload

这样访问会直接跳转到百度主页
image

常见的flag

flag 作用
last 基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个
一旦此rewrite规则重写完成后,就不再被后面其它的rewrite规则进行处理
而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break 中止Rewrite,不再继续匹配一旦此rewrite规则重写完成后,由UserAgent对新的URL重新发起请求,
且不再会被当前location内的任何rewrite规则所检查
redirect 以临时重定向的HTTP状态302返回新的URL
permanent 以永久重定向的HTTP状态301返回新的URL

rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法如下:

标识符 意义
^ 必须以^后的实体开头
$ 必须以$前的实体结尾
. 匹配任意字符
[] 匹配指定字符集内的任意字符
[^] 匹配任何不包括在指定字符集内的任意字符串
匹配
() 分组,组成一组用于匹配的实体,通常会有

捕获子表达式,可以捕获放在()之间的任何文本,比如:

^(hello|sir)$       //字符串为“hi sir”捕获的结果:$1=hi$2=sir

//这些被捕获的数据,在后面就可以当变量一样使用了

if

语法:if (condition) {...}
应用场景:

  • server段
  • location段

常见的condition

  • 变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
  • 以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
  • 正则表达式的模式匹配操作
    • ~:区分大小写的模式匹配检查
    • ~*:不区分大小写的模式匹配检查
    • !和!*:对上面两种测试取反
  • 测试指定路径为文件的可能性(-f,!-f)
  • 测试指定路径为目录的可能性(-d,!-d)
  • 测试文件的存在性(-e,!-e)
  • 检查文件是否有执行权限(-x,!-x)

基于浏览器实现分离案例

if ($http_user_agent ~ Firefox) {
  rewrite ^(.*)$ /firefox/$1 break;
}

if ($http_user_agent ~ MSIE) {
  rewrite ^(.*)$ /msie/$1 break;
}

if ($http_user_agent ~ Chrome) {
  rewrite ^(.*)$ /chrome/$1 break;
}

防盗链案例

location ~* .(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.idfsoft.com/403.html;
  }
}

反向代理与负载均衡

nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力。

nginx实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx发布的路径去读取,而不需要从后台服务器获取了。

但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync做服务端自动同步或者使用NFS、MFS分布式共享存储。

Http Proxy模块,功能很多,最常用的是proxy_pass和proxy_cache

如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模块,用来清除指定的URL缓存。这个集成需要在安装nginx的时候去做,如:
./configure --add-module=../ngx_cache_purge-1.0 ......

nginx通过upstream模块来实现简单的负载均衡,upstream需要定义在http段内

在upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash,如

upstream idfsoft.com {
  ip_hash;
  server 127.0.0.1:9080 weight=5;
  server 127.0.0.1:8080 weight=5;
  server 127.0.0.1:1111;
}

注意:这个方法本质还是轮询,而且由于客户端的ip可能是不断变化的,比如动态ip,代理,FQ等,因此ip_hash并不能完全保证同一个客户端总是由同一个服务器来处理。

定义好upstream后,需要在server段内添加如下内容

server {
  location / {
    proxy_pass http://idfsoft.com;
  }
}

环境

主机 ip 安装 环境
nginx 192.168.23.148 nginx CentOS 8
yc1 192.168.23.142 httpd CentOS 8
yc2 192.168.23.143 httpd CentOS 8

配置

//写一个测试文件到yc1
[root@yc1 ~]# echo "this is rs1" > /var/www/html/index.html

//启动服务
[root@yc1 ~]# systemctl start httpd
[root@yc1 ~]# ss -antl
State     Recv-Q     Send-Q          Local Address:Port         Peer Address:Port     
LISTEN    0          128                   0.0.0.0:22                0.0.0.0:*        
LISTEN    0          128                         *:80                      *:*        
LISTEN    0          128                      [::]:22                   [::]:*  

  

//写一个测试文件到yc2
[root@yc2 ~]# echo "this is rs2" > /var/www/html/index.html

//启动服务
[root@yc2 ~]# systemctl start httpd
[root@yc2 ~]# ss -antl
State     Recv-Q     Send-Q          Local Address:Port         Peer Address:Port     
LISTEN    0          128                   0.0.0.0:22                0.0.0.0:*        
LISTEN    0          128                         *:80                      *:*        
LISTEN    0          128                      [::]:22                   [::]:*  

访问测试

[root@nginx ~]# curl 192.168.23.142
this is rs1

[root@nginx ~]# curl 192.168.23.143
this is rs2

配置nginx

[root@nginx html]# vim /usr/local/nginx/conf/nginx.conf

...
...
    upstream  index.html {                                  //跟server平级
        server 192.168.23.142;
        server 192.168.23.143;
    }

    server {
        listen       80;
        server_name  localhost;

...
...

        location / {
            proxy_pass http://index.html;
        }

[root@nginx html]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx html]# nginx -s reload

访问nginx的IP

[root@nginx ~]# curl 192.168.23.148
this is rs1

[root@nginx ~]# curl 192.168.23.148
this is rs2

weight用法

[root@nginx html]# vim /usr/local/nginx/conf/nginx.conf
    upstream index.html {
        server 192.168.23.142 weight=2;
        server 192.168.23.143;
    }

可以看到前两次都是访问到yc1的资源,第三次才访问到yc2的资源

[root@nginx ~]# curl 192.168.23.148
this is rs1

[root@nginx ~]# curl 192.168.23.148
this is rs1

[root@nginx ~]# curl 192.168.23.148
this is rs2
原文地址:https://www.cnblogs.com/Ycqifei/p/14839391.html