How to use Nginx to play as prox

2018-07-10  本文已影响0人  凸大愚若智凸

This post is for those familiar with nodejs, npm and Nginx.

Consider such a scenario:

  1. You build a Web App based on react (who doesn't build Web App based on react nowadays), say localhost:3000 on your machine. Right, it's default by npm start.
  2. You build another Web API service to expose your data. You got it right again, it's based on json-server. Let's setup it with json-server --port 3001 --watch db.json -r route.json (What the hell is this -r route.json for? Be patient, you'll get there.)

In your development envrionment, you'd access localhost:3000/<view-uri> to get pages, while access API data thru some URL like localhost:3001/<api-uri>. But in the production environment you probably want your client App to always visit http://your-web-site/<uri> thru port 80 which is the http server port by default, no matter it's for simple or for safe. But here we have two services actually, and use non-default http service port. So now what?
Here Nginx comes to rescue.

server {
    location / {
        proxy_pass http://localhost:3000/; # should end with '/'
    }

    location /api {
        proxy_pass http://localhost:3001/; # should end with '/'
    }
}

Important
Make sure that the URL of proxy_pass is ended with /.

Wait a second, originally you access the API thru localhost:3001/users, but now it becomes localhost:3001/api/users. There's an extra part api in between localhost:3001 and users. Emmm, that's a problem.
Remember when we start json-server, we input a parameter of -r route.json? Yes, that's for the routing. You can check json-server --help for the explanation (actually the only way you can nail this is experimenting), here below is the content of route.json.

{
    "/api/:id": "/:id"
}

With route.json when you visit localhost/api/users it'll be redirected to localhost:3001/users.
Tatata...
Now you get the idea for how to extend for more service and add more routes for the URL change.
Refer to Nginx Beginners Guide for more details.
Enjoy it.

上一篇 下一篇

猜你喜欢

热点阅读