【问题标题】:How to redirect request to Nginx to external server?如何将请求重定向到 Nginx 到外部服务器?
【发布时间】:2016-12-16 20:51:32
【问题描述】:

我已经阅读了文档并看到了许多关于如何通过 Nginx 代理请求的示例,但我仍然无法使简单的示例工作。
当我输入http://localhost:5050/maps/....之类的网址时,我希望 Nginx 使用该网址向 Google 地图发出请求。
这是我的配置文件:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       5050;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #root   html;
            #index  index.html index.htm;
            #access_log off;
            proxy_pass http://maps.googleapis.com;
            proxy_pass_request_body on;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }   
    }
}

但是当我向http://localhost:5050/maps/...发出请求时,我得到了标准的 404 页面“未找到”。
error.log 文件显示“系统找不到指定的文件”的多个条目,这很奇怪 - 我没有要求磁盘上的任何文件。
最重要的是,我在 Fiddler 中查找 - 没有对 maps.googleapis.com 的传出请求。
我在这里做错了什么?示例网址为http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA

【问题讨论】:

    标签: nginx http-proxy nginx-location


    【解决方案1】:

    我认为问题是 - 我没有正确重新启动 nginx(我在 Windows 上),所以当我关闭 nginx.exe 时,仍然有一个进程可以继续服务请求。
    无论如何,这是一个适合我的版本:

    worker_processes  1;
    
    error_log logs/error.log;
    pid        logs/nginx.pid;
    
    
    events {
        worker_connections  1024;
    }
    
    
    http {
        include       mime.types;
        default_type  application/octet-stream;
    
        sendfile        on;
    
        keepalive_timeout  2000;
    
        server {
            listen       5050;
            server_name  localhost;
    
            location / {
                proxy_pass https://maps.googleapis.com;
                proxy_pass_request_body on;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            }   
        }
    }
    

    【讨论】:

    • 您原来的问题是这一行:proxy_set_header Host $host; 这会将“localhost”作为 Host 标头发送给 google。看起来你的新的没有那条线。
    • @JoshuaDeWald 我注意到了。那么这有关系吗?谷歌不认识我? :)
    • 是的,除非 google 网络服务器忽略主机标头(例如,它只为单个主机提供服务),否则它可能会导致 404 或其他错误。
    猜你喜欢
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 2013-05-27
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多