This post is for those familiar with nodejs, npm and Nginx.
Consider such a scenario:
- 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
. - 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 withjson-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
thrusudo 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 visitlocalhost
it'll be redirected tolocalhost:3000
, and when you visitlocalhost/api
it'll be redirected tolocalhost: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.