nginx 重写不工作

nginx rewrite not working

我正在尝试设置一个简单的 nginx 服务器作为我的前端 ui 和后端 api 之间的代理。设置相当简单。 UI 向 /api/endpoint 发出所有 api 请求,代理服务器将请求传递给 api。代理还需要重写请求,而不是转到 http://api.location.net/api/endpoint, it goes to http://api.location.net/endpoint. The UI resides on 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 重写的文档似乎没有我需要的。

如果我没理解错的话,这应该会有所帮助

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

注意 proxy_pass 指令中的 URI 部分

If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive:

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