nginx透明代理:它是如何工作的?

时间:2014-02-13 03:08:28

标签: nginx proxy

我有一个在端口8008上运行的透明代理服务器,我想向这个代理发送一些$ uri。这就是我在代理服务器中所拥有的:

server
{
    listen 8008;
    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$request_uri;
    }
    access_log /var/log/nginx/proxy_access.log;
}

这实际上有效 - 如果我在我的任何浏览器设置中放置主机:8008,proxy_access.log将显示如下记录:

myb.row.ser.ip - - [12/Feb/2014:20:09:24 -0600] "GET http://col.stb01.s-msn.com/i/4B/7CC71C50462D34411C88C3623A69A.jpg HTTP/1.1" 200 9075 "http://www.msn.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"

请注意“GET http://col.stb01 ...”部分。

在我的一个虚拟服务器下,我设置了一个位置(示例uri:/www.patterns.com/cat/subcat/sample.html):

location ~* (patterns)
{
    set $hostx "";  
    set $addrs "";  
    if ( $uri ~ "^/(.*?)(/.*)$") {  
        set $hostx $1;  # could be www.patterns.com
        set $addrs $2;  # could be /cat/subcat/sample.html
    }
proxy_pass http://127.0.0.1:8008/http://$hostx$addrs;
    proxy_set_header referer "";
}

上面的代码会将捕获的uri发送到我的代理服务器,但代理服务器看到的内容与proxy_access.log

不同
127.0.0.1 - - [12/Feb/2014:20:44:28 -0600] "GET /http://www.patterns.com/cat/subcat/sample.html HTTP/1.0" 502 574 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"

请注意:"GET /http://www.patterns.co..."中的前导斜杠,我相信这会导致代理服务器返回502代码。

现在我的问题是:在我的位置,如何将正确的uri发送到代理服务器?

谢谢,

1 个答案:

答案 0 :(得分:0)

您应该删除proxy_pass中的“/ http://”部分。

实际上,我真的不明白为什么你需要获得$ hostx和$ addrs,请查看nginx doc

While passing request nginx replaces URI part which corresponds to location with one indicated in proxy_pass directive. But there are two exceptions from this rule when it is not possible to determine what to replace:

if the location is given by regular expression;
if inside proxied location URI is changed by rewrite directive, and this configuration will be used to process request (break):
location  /name/ {
  rewrite      /name/([^/] +)  /users?name=$1  break;
  proxy_pass   http://127.0.0.1;
}
For these cases of URI it is transferred without the mapping.