nginx重写不起作用

时间:2015-01-20 20:14:50

标签: nginx proxy

我试图设置一个简单的nginx服务器作为我的前端ui和我的后端api之间的代理。设置非常简单。 UI向/ api / endpoint发出所有api请求,代理服务器将请求传递给api。代理还需要重写请求,以便转到http://api.location.net/api/endpoint而不是http://api.location.net/endpoint。用户界面位于http://api.location.net。这部分不起作用(我得到500错误),我很确定它与我如何写我的重写规则有关。这是我的nginx配置。

daemon off;
error_log off;

worker_processes 2;
worker_rlimit_nofile 100000;
events {
    worker_connections 50000;
    accept_mutex off;
}

http {
    include /etc/nginx/mime.types;
    access_log off;
    sendfile on;

    server {
        listen 80 default_server;
        server_name  localhost _;

        location / {
            alias /srv/site/;
        }

        location /api/ {
            rewrite ^/api ""; # I think this is the problem
            proxy_pass http://api.location.net;
            proxy_pass_request_headers on;
            proxy_pass_header X-ResponseData;
            proxy_redirect off;
        }
    }
}

任何帮助都会非常感激,nginx对我来说还是比较新的,关于nginx重写的文档似乎没有我需要的。

1 个答案:

答案 0 :(得分:2)

如果我理解你的话,这应该有帮助

location /api/ {
            proxy_pass http://api.location.net/;
            proxy_pass_request_headers on;
            proxy_pass_header X-ResponseData;
            proxy_redirect off;
        }

请注意proxy_pass指令中的URI部分

  

如果使用URI指定了proxy_pass指令,那么当a。时   请求被传递给服务器,这是规范化请求URI的一部分   匹配该位置将替换为指令中指定的URI:

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass