nginx 怎么反向代理到百度?

2016-09-12 08:51:41 +08:00
 whx20202

我试着用了下面的配置文件,结果返货 405 bfe not allowed ,然后我用 tcpdump 和 wireshark 在自己 nginx 上抓包,发现好像, nginx 反向到百度的 http 头,还是我一开始的那个:

我在浏览器输入我自己本地的 nginx 地址: http://127.0.0.1:8080/ 这时候 http 头的 host 肯定是 127.0.0.1

nginx 反向代理的时候,host应该是被他修改,变成: www.baidu.com 才对,实际上没有...。 可是最关键的问题是,我已经设置:

proxy_set_header Host $http_host; 按理来说应该给我转换了

是不是我还有哪里没设置好?

具体配置如下:

http {

    server {   
    listen  8080 default backlog=2048;  
    listen  443 ssl;
 
    server_name  127.0.0.1;  
 
    ssl_certificate /etc/nginx/1.crt;
    ssl_certificate_key /etc/nginx/1.key;

    location /proxy/git/ {   
        proxy_pass https://github.com/;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for; 
        proxy_pass_header Server;

 
        proxy_redirect /  /;  
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;

        }
        error_page   500 502 503 504  /50x.html;   
   }

    ##
    # Basic Settings
    ##

    sendfile on; 
    tcp_nopush on; 
    tcp_nodelay on; 
    keepalive_timeout 65; 
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
19607 次点击
所在节点    NGINX
5 条回复
oott123
2016-09-12 10:17:05 +08:00
proxy_set_header Host $http_host;

proxy_set_header Host www.baidu.com;
whx20202
2016-09-12 10:59:26 +08:00
@oott123 已感谢! 可是您能否告诉我为啥

proxy_set_header Host $http_host; proxy_set_header Host $host; 都不行呢。。
感觉应该是可以的~
oott123
2016-09-12 11:06:05 +08:00
$host 和 $http_host 都是你访问 nginx 的时候的 host ,并不是你反代的那个 host 。$proxy_host 才是你反代的那个 host ,其实你写死也一样,不一定要配置成变量。


$host
in this order of precedence: host name from the request line, or host name from the “ Host ” request header field, or the server name matching a request

---

The ngx_http_proxy_module module supports embedded variables that can be used to compose headers using the proxy_set_header directive:

$proxy_host
name and port of a proxied server as specified in the proxy_pass directive;
jerray
2016-09-12 11:13:35 +08:00
@whx20202 http://serverfault.com/questions/706438/what-is-the-difference-between-nginx-variables-host-http-host-and-server-na

$host 和 $http_host 是指向你自己的机器的。要代理到其他网站, HTTP Header 里的 Host 就要设置成目标站点的域名,这样请求发到目标站点,目标站点的 Web 服务器才能正确处理请求。
whx20202
2016-09-12 11:19:20 +08:00
@jerray 非常感谢您和上面那位同学。。了解了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/305568

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX