taylorc93
taylorc93

Reputation: 3716

nginx rewrite not working

I'm trying to set up a simple nginx server to act as a proxy between my front end ui and my back end api. The setup is fairly simple. The UI makes all api requests to /api/endpoint and the proxy server passes the request to the api. The proxy also needs to rewrite the request so that instead of going to http://api.location.net/api/endpoint, it goes to http://api.location.net/endpoint. The UI resides on http://api.location.net. This part isn't working (i get a 500 error) and I'm pretty sure it has to do with how I'm writing my rewrite rule. Here's my nginx config.

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;
        }
    }
}

Any help would be greatly appreciated, nginx is still fairly new for me and the documentation on nginx rewrite doesn't seem to have what I need.

Upvotes: 0

Views: 637

Answers (1)

SuddenHead
SuddenHead

Reputation: 1503

If I understood you right, this should help

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

Note the URI part at proxy_pass directive

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

Upvotes: 2

Related Questions