美文网首页
How to use Nginx to play as prox

How to use Nginx to play as prox

作者: 凸大愚若智凸 | 来源:发表于2018-07-10 19:55 被阅读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.

  • Install Nginx thru sudo apt install nginx (suppose you're using Ubuntu)
  • Change Nginx configure file of /etc/nginx/sites-available/default to add below code:
server {
    location / {
        proxy_pass http://localhost:3000/; # should end with '/'
    }

    location /api {
        proxy_pass http://localhost:3001/; # should end with '/'
    }
}
  • Restart Nginx by sudo systemctl restart nginx
    Now when you visit localhost it'll be redirected to localhost:3000, and when you visit localhost/api it'll be redirected to localhost:3001/api.

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.

相关文章

网友评论

      本文标题:How to use Nginx to play as prox

      本文链接:https://www.haomeiwen.com/subject/cgpqpftx.html