laner107
laner107

Reputation: 220

How To Use A Proxy Pass For All Incoming API Request

I am setting up a server to host my website using nginx but i am having trouble with my backend working. Currently I only use Restful APIs and am trying to use proxypasses within nginx to hit my backend, but do I have to add a location for every api endpoint. For example my backend server is ran from pm2 on localhost:5000, all of my endpoints entail http://myip/api/(my-endpoint), if I setup the nginx to look like this:

location / {
                try_files $uri $uri/ =404;
        }

        location /api {
                proxy_pass http://localhost:5000/api;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

it still doesnt work. What is the best way to go about setting up nginx to handle all requests from my front end to backend? Thank you!

Upvotes: 0

Views: 2927

Answers (1)

Nickleby
Nickleby

Reputation: 103

When you don't use a slash / at the end of the proxy URL, it adds /api to the later proxy_pass so you eventually get http://localhost:5000/api/api.

Try using a slash by the end of the root URL:

    location /api {
        proxy_pass http://localhost:5000/;
    }

Upvotes: 1

Related Questions