nginx rewrite与proxy_pass详解

最近接触到了nginx的 proxy_pass 与 rewrite,网上查了很多资料,在这里记录一下,学习学习。

说明

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地址;
  • 如果正则表达式(regex)匹配到了请求的URI(request URI),这个URI会被后面的replacement替换(URL会改变)
  • rewrite的定向会根据他们在配置文件中出现的顺序依次执行
  • 通过使用flag可以终止定向后进一步的处理
  • Rewrite根据nginx提供的全局变量或自己设置的变量,结合正则表达式和标志位实现url重写和者重定向。
  • Rewrite和location类似,都可以实现跳转,区别是rewrite是在同一域名内更改url,而location是对同类型匹配路径做控制访问,或者proxy_pass代理到其他服务器。
  • Rewrite和location执行顺序:
    • 执行server下的rewrite
    • 执行location匹配
    • 执行location下的rewrite
  • 如果replacement以“http://”, “https://”, or “$scheme”开头,处理将会终止,请求结果会以重定向的形式返回给客户端(client)
  • 如果replacement字符串里有新的request参数,那么之前的参数会附加到其后面,如果要避免这种情况,那就在replacement字符串后面加上“?”,eg:
     rewrite ^/users/(.*)$ /show?user=$1? last;
  • 如果正则表达式(regex)里包含“}” or “;”字符,需要用单引号或者双引号把正则表达式引起来

可选的flag参数如下:

  • last
  1. 结束当前的请求处理,用替换后的URI重新匹配location;
  2. 可理解为重写(rewrite)后,发起了一个新请求,进入server模块,匹配location;
  3. 如果重新匹配循环的次数超过10次,nginx会返回500错误;
  4. 返回302 http状态码
  5. 浏览器地址栏显示重地向后的url
  • break
  1. 结束当前的请求处理,使用当前资源,不在执行location里余下的语句;
  2. 返回302 http状态码 ;
  3. 浏览器地址栏显示重地向后的url
  •  redirect
  1. 临时跳转,返回302 http状态码;
  2. 浏览器地址栏显示重地向后的url
  • permanent
  1. 永久跳转,返回301 http状态码;
  2. 浏览器地址栏显示重定向后的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;
  }
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;
  1. rewrite语法格式
  2. IF判断和内置全局环境变量

 

proxy_pass

Syntax:    proxy_pass URL;
Default:    —
Context:    location, if in location, limit_except
  • 不影响浏览器地址栏的url
  • 设置被代理server的协议和地址,URI可选(可以有,也可以没有)
  • 协议可以为http或https
  • 地址可以为域名或者IP,端口可选;eg:
     proxy_pass http://localhost:8000/uri/;
  •  如果一个域名可以解析到多个地址,那么这些地址会被轮流使用,此外,还可以把一个地址指定为 server group(如:nginx的upstream), eg:

     

    upstream backend {
        server backend1.example.com       weight=5;
        server backend2.example.com:8080;
        server unix:/tmp/backend3;
     
        server backup1.example.com:8080   backup;
        server backup2.example.com:8080   backup;
    }
     
    server {
        location / {
            proxy_pass http://backend;
        }
    }
  • server name, port, URI支持变量的形式,eg:
    proxy_pass http://$host$uri;

这种情况下,nginx会在server groups(upstream后端server)里搜索server name,如果没有找到,会用dns解析

请求的URI按照下面的规则传给后端server

  1. 如果proxy_pass的URL定向里包括URI,那么请求中匹配到location中URI的部分会被proxy_pass后面URL中的URI替换,eg:
    location /name/ {
        proxy_pass http://127.0.0.1/remote/;
    }
    请求http://127.0.0.1/name/test.html 会被代理到http://example.com/remote/test.html
  2. 如果proxy_pass的URL定向里不包括URI,那么请求中的URI会保持原样传送给后端server,eg:
    location /name/ {
        proxy_pass http://127.0.0.1;
    }
    
    请求http://127.0.0.1/name/test.html 会被代理到http://127.0.0.1/name/test.html
  3.  一些情况下,不能确定替换的URI
     
    1. location里是正则表达式,这种情况下,proxy_pass里最好不要有URI
    2. 在proxy_pass前面用了rewrite成功,如下,这种情况下,proxy_pass中的URL是无效的,eg:

               location /name/ {
                  rewrite    /name/([^/]+) /users?name=$1 break;
                  proxy_pass http://127.0.0.1/useless;   #/useless无效
               }

          疑惑?  往下看。

   4.如果proxy_pass指令指定了URI,那么请求中匹配location部分的URI将会被替换:

location /name {  

    proxy_pass http://127.0.0.1:8080/other;  

}  

#http://exampe.org/name/a.jhtml将会被转发给:  

#http://127.0.0.1:8080/other/a.jhtml  

   5.如果location中使用了uri,但是proxy_pass中没有使用,那么请求的uri将会全部添加到proxy_pass指定的路径之后。

location /name {  

    proxy_pass http://127.0.0.1:8080;  

}  

#请求url为http://example.org/name/a.jhtml将会被转发到  

#http://127.0.0.1:8080/name/a.jhtml  

    6.如果location中使用了正则表达式,那么在proxy_pass指令中不应该指定uri,否则uri的替换是无法断定的

    7.如果在location中使用了“rewrite”指令(break)对请求的uri进行了修改,那么proxy_pass指令中的uri将会被忽略,被rewrite之后的全量uri将会传递给server

location /name {  

    rewrite /name/([^/]+) /users?name=$1 break;  

    proxy_pass http://127.0.0.1/useless;  

}  

#http://exmaple.org/name/zhangsan,  将会转发到     #http://127.0.0.1/users?name=zhangsan  

   8.其中server名称、端口、uri等均可以使用变量:

proxy_pass http://$host$uri;  

##等价于  

proxy_pass $request;  

 

例子1:

需求信息如下:

  • html、js、css、jpg等静态资源尽量走nginx;
  • 首页默认不带index.html 但是也走nginx;
  • 前后端分离+优化url(笔者不确定这种优化是否起反作用),/s/?wd=xxx  -->  list.html?wd=xxx   /details/{num}  -->  details.html?u={num}
  • 其余请求转发到8000端口jetty容器(java应用);
  • itblacklist.cn的请求及权重永久转到www.itblacklist.cn;
  • tucao.itblacklist.cn转到php应用;

直接上配置

server {
	server_name www.itblacklist.cn;
	listen 80;
	root /opt/apps/blacklist/page;		#nginx server根目录
	
	# =精准匹配 /首页 该规则只匹配首页
	location =/ {}
	# ~* 不区分大小写的正则匹配  匹配所有以.html .gif等结尾的请求
	location ~* \.(html|gif|jpg|ico|js|css|map|svg|eot|tff|woff|woff2)$ {}
	
	# ^~ 匹配以某个开头的请求  该处匹配以/s/开头的请求
	location ^~ /s/ {
		rewrite /s/(.+)$ /$1 break;	
		proxy_pass http://www.itblacklist.cn/list.html;
		#... proxy头信息等
                proxy_set_header Host $host;
                proxy_set_header X-Real-Ip $remote_addr;
                proxy_set_header X-Forwarded-For $remote_addr;
	}
	location ~* /details/([0-9]+)$ {
		rewrite /details/(.+)$ /details.html?u=$1 break;
	}
	location / {
		proxy_pass http://www.itblacklist.cn:8000;
		#...
                proxy_set_header Host $host;
                proxy_set_header X-Real-Ip $remote_addr;
                proxy_set_header X-Forwarded-For $remote_addr;
	}
}
server {
	server_name itblacklist.cn;
	rewrite ^(.*)$ http://wwww.itblacklist.cn$1 permanent;
}
server {
	server_name tucao.itblacklist.cn;
	
	location / {
		proxy_pass http://www.itblacklist.cn:9000;
		#...
                proxy_set_header Host $host;
                proxy_set_header X-Real-Ip $remote_addr;
                proxy_set_header X-Forwarded-For $remote_addr;
	}
}

重新加载nginx配置: nginx -s reload

例子2

location /Shep.ElicenseWeb/ {
    rewrite ^/Shep.ElicenseWeb/(.*) /$1 break;
    proxy_pass http://localhost:82;
}

    http://192.168.64.76/Shep.ElicenseWeb/Public/OutputDocuments.ashx?uinz=12009718&iinbin=860610350635 
Should be redirected to:

   http://localhost:82/Public/OutputDocuments.ashx?uinz=12009718&iinbin=860610350635 
 

例子3

3.1 1location without regular expression

  1. If the proxy_pass directive is specified without a URI,

    location /app/ {
        proxy_pass      http://192.168.154.102;
    }
    
    test.com/app/xxxxx =>  http://192.168.154.102/xxxxx
    
  2. If the proxy_pass directive is specified with a URI:

    location /app/ {
        proxy_pass      http://192.168.154.102/maped_dir/;
    }
    
    test.com/app/xxxxx =>  http://192.168.154.102/maped_dir/xxxxx
    
  3. Forward the requested Host header

    By default, the Host header from the request is not forwarded, but is set based on the proxy_pass statement. To forward the requested Host header, it is necessary to use:

    proxy_set_header Host $host;
    

3.2. location with regular expression

  1. If the location is given by regular expression, can not be a URI part in proxy_pass directive, unless there are variables in the directive.

    location  ~ ^/app/(.*)$ {
        # proxy_pass   http://127.0.0.1/some_dir;       # error
        proxy_pass   http://127.0.0.1/some_dir/$1;      # ok
    }
    

     

  2. variables in proxy_pass directive:

    location ~ ^/app/(.*)$ {
        proxy_pass       http://192.169.154.102:$1;
    }
    
    test.com/app/8081 => http://192.168.154.102:8081
    

    and:

    location ~ ^/app/(.*)$ {
        proxy_pass       http://192.169.154.102:9999/some_dir/$1;
    }
    
    test.com/app/request/xxxxx => http://192.168.154.102:9999/some_dir/xxxxx
    
  3. with a rewrite directive in the location:

    If the rewrite rule is hit, the URI specified in the directive is ignored and the full changed request URI is passed to the server:如果rewrite匹配到了,则使用新的URL传送给proxy_pass

        location  /app/ {
            rewrite    ^/app/hit/(.*)$ /hit_page.php?path=$1 break;
            proxy_pass   http://192.168.154.102:9999/some_dir/;
        }

/app/hit/some/request/?name=xxxxx    rewrite匹配成功

=> http://192.168.154.102:9999/hit_page.php?path=some/request/&name=xxxxx

/app/not_hit/some/request/?name=xxxxx  rewrite匹配失败

=> http://192.168.154.102:9999/some_dir/not_hit/some/request/?name=xxxxx

 

参考:

https://jonathanmh.com/proxy-rewrite-api-endpoint-domain-segment-nginx/

https://www.liaohuqiu.net/posts/nginx-proxy-pass/

https://serverfault.com/questions/379675/nginx-reverse-proxy-url-rewrite

https://superuser.com/questions/690916/how-to-make-nginx-rewrite-uris-in-http-body-content

https://yq.aliyun.com/articles/9095

https://blog.csdn.net/mdjhzgj/article/details/78442422

https://www.cnblogs.com/luxianghao/p/6807081.html

https://www.jianshu.com/p/10ecc107b5ee

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值