【问题标题】:How can I proxypass a port range on nginx?如何在 nginx 上代理传递端口范围?
【发布时间】:2021-04-26 00:39:09
【问题描述】:

我的 Node.js 服务器默认侦听端口 5000,可以使用 localhost:5000 访问。我让我的 nginx 服务器使用以下配置将任何请求传递给服务器:

server {

        root /var/www/example.com/html;
        index index.html index.htm index.nginx-debian.html;

        server_name example.com www.example.com;

        location / {
                proxy_pass http://localhost:5000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;

        }

    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


}
server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


        listen 80;
        listen [::]:80;

        server_name example.com www.example.com;
    return 404; # managed by Certbot




}


这在大多数情况下都有效,除非我重定向到不同的端口。稍后我调用 res.redirect('localhost:5001/user') 例如这会导致 nginx 挂起。它似乎无法连接到 5000 以外的任何其他端口。如何设置我的 nginx 服务器以接受 5000 以外的端口范围的重定向?

我尝试将 5000 替换为 $server_port,但这似乎也不起作用。

【问题讨论】:

    标签: node.js nginx


    【解决方案1】:

    所以我从问题中得到的是你希望 NGINX 也响应其他端口。

    你可以拥有这种东西。如果你想要端口范围,NGINX 不可能提供端口范围。如果你想让 NGINX 监听 1000 个不同的端口,你必须在 NGINX 配置文件中明确提到 1000 个不同的监听语句,如下所示:

    listen 5001;
    listen 443;
    listen ...;
    listen ...;
    listen ...;
    

    【讨论】:

    • 我如何让它代理请求到正确的端口呢?代理总是通过 localhost:5000,不管端口是什么。
    • 好的。所以你应该有类似的server{...} 块,你可以在不同的端口上listen,根据你的方便,你可以proxy_pass to different ports
    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 2021-05-29
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 2013-08-29
    • 2020-09-27
    • 2017-05-16
    相关资源
    最近更新 更多