Linux下Nginx服务Rewrite和Proxy_Pass

Nginx_Rewrite

  • 一、介绍
    1. Rewrite根据nginx提供的全局变量或自己设置的变量,结合正则表达式和标志位实现url重写和者重定向。
    2. Rewrite和location类似,都可以实现跳转,区别是rewrite是在同一域名内更改url,而location是对同类型匹配路径做控制访问,或者proxy_pass代理到其他服务器。
    3. Rewrite和location执行顺序:
      • 执行server下的rewrite
      • 执行location匹配
      • 执行location下的rewrite
  • 二、语法和参数说明
    1. rewrite语法格式
    rewrite        <regex>        <replacement>        <flag>;
     关键字        正则表达式         代替的内容         重写类型
    
    Rewrite:一般都是rewrite
    Regex:可以是字符串或者正则来表示想要匹配的目标URL
    Replacement:将正则匹配的内容替换成replacement
    Flag:flag标示,重写类型:
      - last:本条规则匹配完成后,继续向下匹配新的location URI规则;相当于Apache里德(L)标记,表示完成rewrite,浏览器地址栏URL地址不变;一般写在server和if中;
      - break:本条规则匹配完成后,终止匹配,不再匹配后面的规则,浏览器地址栏URL地址不变;一般使用在location中;
      - redirect:返回302临时重定向,浏览器地址会显示跳转后的URL地址;
      - permanent:返回301永久重定向,浏览器地址栏会显示跳转后的URL地址;
    
    server {
      # 访问 /last.html 的时候,页面内容重写到 /index.html 中,并继续后面的匹配,浏览器地址栏URL地址不变
      rewrite /last.html /index.html last;
    
      # 访问 /break.html 的时候,页面内容重写到 /index.html 中,并停止后续的匹配,浏览器地址栏URL地址不变;
      rewrite /break.html /index.html break;
    
      # 访问 /redirect.html 的时候,页面直接302定向到 /index.html中,浏览器地址URL跳为index.html
      rewrite /redirect.html /index.html redirect;
    
      # 访问 /permanent.html 的时候,页面直接301定向到 /index.html中,浏览器地址URL跳为index.html
      rewrite /permanent.html /index.html permanent;
    
      # 把 /html/*.html => /post/*.html ,301定向
      rewrite ^/html/(.+?).html$ /post/$1.html permanent;
    
      # 把 /search/key => /search.html?keyword=key
      rewrite ^/search\/([^\/]+?)(\/|$) /search.html?keyword=$1 permanent;
      
      # 把当前域名的请求,跳转到新域名上,域名变化但路径不变
      rewrite ^/(.*) http://www.jd.com/$1 permanent;
      }
    
    1. IF判断和内置全局环境变量
    if (表达式) {
    }
    
    #当表达式只是一个变量时,如果值为空或任何以0开头的字符串都会当做false直接比较变量和内容时,使用=或!=~正则表达式匹配,~*不区分大小写的匹配,!~区分大小写的不匹配
    
    $args :这个变量等于请求行中的参数,同$query_string
    $content_length : 请求头中的Content-length字段。
    $content_type : 请求头中的Content-Type字段。
    $document_root : 当前请求在root指令中指定的值。
    $host : 请求主机头字段,否则为服务器名称。
    $http_user_agent : 客户端agent信息
    $http_cookie : 客户端cookie信息
    $limit_rate : 这个变量可以限制连接速率。
    $request_method : 客户端请求的动作,通常为GET或POST。
    $remote_addr : 客户端的IP地址。
    $remote_port : 客户端的端口。
    $remote_user : 已经经过Auth Basic Module验证的用户名。
    $request_filename : 当前请求的文件路径,由root或alias指令与URI请求生成。
    $scheme : HTTP方法(如http,https)。
    $server_protocol : 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。
    $server_addr : 服务器地址,在完成一次系统调用后可以确定这个值。
    $server_name : 服务器名称。
    $server_port : 请求到达服务器的端口号。
    $request_uri : 包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”。
    $uri : 不带请求参数的当前URI,$uri不包含主机名,如”/foo/bar.html”。
    $document_uri : 与$uri相同。
     
    例子:
    URL:http://localhost:81/download/stat.php?id=1585378&web_id=1585378
    Server_Dir:/var/www/html
    $host:localhost
    $server_port:81
    $request_uri:/download/stat.php?id=1585378&web_id=1585378
    $document_uri:/download/stat.php
    $document_root:/var/www/html
    $request_filename:/var/www/html/download/stat.php
    
    # 如果文件不存在则返回400
    if (!-f $request_filename) {
        return 400;
    }
    
    # 如果host是www.360buy.com,则301到www.jd.com中
    if ( $host != "www.jd.com" ){
        rewrite ^/(.*)$ https://www.jd.com/$1 permanent;
    }
    
    # 如果请求类型是POST则返回405,return不能返回301,302
    if ($request_method = POST) {
        return 405;
    }
    
    # 如果参数中有 a=1 则301到指定域名
    if ($args ~ a=1) {
        rewrite ^ http://example.com/ permanent;
    }
    
    - 文件名及参数重写
     location = /index.html {
     # 修改默认值为
     set $name test;
    
     # 如果参数中有 name=xx 则使用该值
     if ($args ~* name=(\w+?)(&|$)) {
         set $name $1;
     }
    
     # permanent 301重定向
     rewrite ^ /$name.html permanent;
    }
    
    - 隐藏真实目录
    server {
      root /var/www/html;
      # 用 /html_test 来掩饰 html
      location / {
          # 使用break拿一旦匹配成功则忽略后续location
          rewrite /html_test /html break;
      }
    
      # 访问真实地址直接报没权限
      location /html {
          return 403;
      }
    }
    
    - 禁止指定IP访问
     location / {
            if ($remote_addr = 192.168.1.253) {
                    return 403;
            }
     }
    
    - 如果请求的文件不存在,则反向代理到localhost 。这里的break也是停止继续rewrite
    if (!-f $request_filename){
        break;
        proxy_pass http://127.0.0.1;
    }
    
    - 对/images/bla_500x400.jpg文件请求,重写到/resizer/bla.jpg?width=500&height=400地址,并会继续尝试匹配location。
    rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3? last;
    

Proxy_Pass

  • Proxy_pass反向代理,用的是nginx的Proxy模块。
第一种:
location /proxy/ {
    proxy_pass http://127.0.0.1/;
}
代理到URL:http://127.0.0.1/test.html


第二种:
location /proxy/ {
    proxy_pass http://127.0.0.1;  #少/
}
代理到URL:http://127.0.0.1/proxy/test.html


第三种:
location /proxy/ {
    proxy_pass http://127.0.0.1/aaa/;
}
代理到URL:http://127.0.0.1/aaa/test.html


第四种(相对于第三种,最后少一个 / )
location /proxy/ {
    proxy_pass http://127.0.0.1/aaa;
}
代理到URL:http://127.0.0.1/aaatest.html
- proxy_set_header  Host  $host;  作用web服务器上有多个站点时,用该参数header来区分反向代理哪个域名。比如下边的代码举例。
- proxy_set_header X-Forwarded-For  $remote_addr; 作用是后端服务器上的程序获取访客真实IP,从该header头获取。部分程序需要该功能。
- Proxy_pass配合upstream实现负载均衡
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
 
    upstream core_tomcat {
      server 192.168.1.253:80      weight=5  max_fails=3 fail_timeout=30;
      server 192.168.1.252:80      weight=1  max_fails=3 fail_timeout=30;
      server 192.168.1.251:80      backup;
    }

    server {
        listen       80;
        server_name  www.jd.com;
        location /web {
            proxy_pass http://core_tomcat;
            proxy_set_header  Host  $host;
        }
    }
 }
  • Nginx负载均衡的几种模式
    • 轮询:每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,就不在分配;
    upstream core_tomcat {
        server 192.168.1.253:80      max_fails=3 fail_timeout=30;
        server 192.168.1.252:80      max_fails=3 fail_timeout=30;
     }
    
    • 权重轮询:根据后端服务器性能不通配置轮询的权重比,权重越高访问的比重越高;
    upstream core_tomcat {
        server 192.168.1.253:80      weight=2  max_fails=3 fail_timeout=30;
        server 192.168.1.252:80      weight=8  max_fails=3 fail_timeout=30;
    }
    #假如有十个请求,八个会指向第二台服务器,两个指向第一台;
    
    • IP_Hash:根据请求的ip地址hash结果进行分配,第一次分配到A服务器,后面再请求默认还是分配到A服务器;可以解决Session失效重新登录问题;
    upstream core_tomcat {
      ip_hash;
      server 192.168.1.253:80      max_fails=3 fail_timeout=30;
      server 192.168.1.252:80      max_fails=3 fail_timeout=30;
    }
    
    • Fair:按后端服务器的响应时间来分配请求,响应时间短的优先分配;
    upstream core_tomcat {
      fair;
      server 192.168.1.253:80      max_fails=3 fail_timeout=30;
      server 192.168.1.252:80      max_fails=3 fail_timeout=30;
    }
    
    • Url_hash:按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效;
    upstream core_tomcat {
      hash  $request_uri;
      server 192.168.1.253:80      max_fails=3 fail_timeout=30;
      server 192.168.1.252:80      max_fails=3 fail_timeout=30;
    }
    

参考文档:

http://www.cnblogs.com/mikeluwen/p/7116967.html

https://www.cnblogs.com/zl0372/articles/nginx.html

https://blog.csdn.net/qq_28602957/article/details/61615876

http://blog.51cto.com/liqilong2010/1837126

https://www.cnblogs.com/likwo/p/6513117.html