server {
listen 80;
listen [::]:80;
root /var/www/example.com/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com;
location / {
try_files $uri $uri/ =404;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
我已经为 SSL 证书设置了 Nginx。我现在需要做什么才能将所有外部请求从 转发https://example.com:<port>
到localhost:<port>
?
例如,HTTP 查询https://example.com:3000应转发到监听 localhost:3000 的本地 NodeJS 服务器,并且https://example.com:3001应该转发到localhost:3001,依此类推。
答案1
Nginx 反向代理可以帮助您重定向 URL 和端口
例如:下面的配置块重定向来自http://example.com:3000更改为 127.0.0.1:3000
upstream app_nodejs {
server 127.0.0.1:3000;
}
upstream web_nodejs {
server 127.0.0.1:3001;
}
server {
listen 3000 default ssl;
listen [::]:3000;
ssl on;
ssl_certificate /root/certs/app.crt;
ssl_certificate_key /root/certs/app.key;
server_name example.com;
if ($ssl_protocol = "") {
rewrite ^ https://$server_name$request_uri? permanent;
}
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_pass https://app_nodejs;
proxy_redirect off;
}
}
server {
listen 3001 default ssl;
listen [::]:3001;
ssl on;
ssl_certificate /root/certs/web.crt;
ssl_certificate_key /root/certs/web.key;
server_name example.com;
if ($ssl_protocol = "") {
rewrite ^ https://$server_name$request_uri? permanent;
}
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_pass https://web_nodejs;
proxy_redirect off;
}
}