解决Nginx反向代理不会自动对特殊字符进行编码的问题 如gitblit中的~波浪线

问题起因是利用Nginx做反向代理的时候,需要访问如下链接
http://192.168.14.141/iserver/services/3D-0524hd/rest/realspace/datas/0524hd/data/path/Tile_+003_+011/Tile_+003_+011_L5_00003.s3m
其中192.168.14.141被反向代理到了192.168.14.141:8090
实际请求的时候返回404,通过查看服务日志,发现服务器收到的Nginx请求确实是这个链接(注意后半部分):

http://192.168.14.141/iserver/services/3D-0524hd/rest/realspace/datas/0524hd/data/path/Tile_+003_+011/Tile_+003_+011_L5_00003.s3m

如果我直接请求8090端口,服务器实际收到的请求是下面这样:

http://192.168.14.141/iserver/services/3D-0524hd/rest/realspace/datas/0524hd/data/path/Tile_%2B003_%2B011/Tile_%2B003_%2B011_L5_00003.s3m

’+’ 号应该被编码未‘%2B’,但是Nginx没有将其编码,导致请求404

手动将+号写成%2B请求到Nginx, Nginx请求目标服务器时还是以+号的形式请求。

解决办法:手动处理一下编码的问题

location /server {
    set $modified_uri $request_uri;
    if ($modified_uri ~ "^/([\w]{2})(/.*)") {
        set $modified_uri $1;
    }
    proxy_pass http://192.168.14.141:8090$modified_uri;
}

详见:https://stackoverflow.com/questions/31266629/nginx-encoding-normalizing-part-of-uri

附官方文档:

If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:

如果proxy_pass没有指定具体的URI,那么请求Nginx的URI将原封不动的被转发到目标服务器。 即便是手动将+号编码,但是Nginx貌似会对其进行解码,最后发送出去的请求仍然是没有编码的。
————————————————
版权声明:本文为CSDN博主「傲娇的鲤鱼」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/LLittleF/article/details/93879077

posted @ 2019-11-22 18:29  威流  阅读(3609)  评论(0编辑  收藏  举报