Gần đây tôi đã thiết lập một VPS trên DigitalOcean để chạy một vài tập lệnh Node.js khác nhau trong cùng một miền.
Bây giờ, bạn không thể có hai ứng dụng Node.js khác nhau nghe trên cùng một cổng, vì vậy bạn phải sử dụng proxy ngược. Nginx thường được sử dụng cho điều đó.
Tôi thiết lập từng ứng dụng Node để chạy trên thư mục con của riêng nó, vì vậy tôi phải chỉnh sửa cấu hình Nginx:
sudo nano /etc/nginx/sites-available/defaultwhich was this:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name hellonode;
location ^~ /assets/ {
gzip_static on;
expires 12h;
add_header Cache-Control public;
}
location / {
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://localhost:3000;
}
}
This configuration allows one Node.js app, running on port 3000, to be the main app served on /
.
I wanted to have an app running under /myservice
, so I created a Node app listening on port 3001 and I added this configuration:
location /myservice {
rewrite ^/myservice/(.*)$ /$1 break;
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://localhost:3001;
}
I checked the configuration was fine using
sudo nginx -tand I restarted nginx:
sudo systemctl restart nginx
More network tutorials:
- Introduction to WebSockets
- How HTTP requests work
- The HTTP Request Headers List
- The HTTP Response Headers List
- HTTP vs HTTPS
- What is an RFC?
- The HTTP protocol
- The HTTPS protocol
- The curl guide to HTTP requests
- Caching in HTTP
- The HTTP Status Codes List
- What is a CDN?
- The HTTP/2 protocol
- What is a port
- DNS, Domain Name System
- The TCP Protocol
- The UDP Protocol
- An introduction to REST APIs
- How to install a local SSL certificate in macOS
- How to generate a local SSL certificate
- How to configure Nginx for HTTPS
- A simple nginx reverse proxy for serving multiple Node.js apps from subfolders
- What is a reverse proxy?