nginx 反向代理 多个nodejs 应用
前言:
- 在阿里云的云服务器的 80 端口已经被其他的服务所使用
- 在阿里云部署 express 项目,使用了3000端
- 浏览器 HTTP 访问 IP 或域名的 80 端口时,可以省略 80 端口号,但其他端口却不能,想省略 3000 端口则需要使用到 nginx 反代理服务器
- 其次,由于阿里云的限制,阿里云的服务没办法绑定到公网 IP 地址,所以要使用到 nginx 反代理服务器
架构原理图

nginx 反向代理配置
server {
listen 80; #监听的端口
server_name demo.example.com; #来访的域名
#修改反向代理地址
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_pass http://127.0.0.1:3000; #实际提供http内容服务的地址
proxy_redirect default;
# root html; # 默认的根目录
#index index.html index.htm; # 默认的首页页面
}
}
注意事项
location 中 proxy_pass 结尾带/接不带的区别
- 在 nginx 中配置 proxy_pass 时,当在后面的url加上了/,相当于是绝对根路径,则nginx不会把location中匹配的路径部分代理走
- 如果没有/,则会把匹配的路径部分也给代理走
举个例子:
location /proxy/ {
proxy_pass http://127.0.0.1:3000/; # 这里有 /
}
域名访问: http://127.0.0.1:3000/proxy/test.html
结论:会被代理到 http://127.0.0.1:3000/test.html 这个url
location /proxy/ {
proxy_pass http://127.0.0.1:81; # 这里没有 /
}
域名访问: http://127.0.0.1:3000/proxy/test.html
结论:会被代理到 http://127.0.0.1:81/proxy/test.html 这个url