You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁止本地网站通过公网IP直接访问,仅经Nginx反向代理?

解决方案:限制后端服务仅本地访问 + Nginx反向代理配置

一、核心修改:让后端服务只绑定本地回环地址

你的服务能通过公网IP直接访问,本质是因为服务默认绑定了0.0.0.0(所有可用网卡),导致公网网卡也会响应端口请求。只需将服务绑定到127.0.0.1或localhost,就能让服务仅接受本地请求,外部无法直接访问。

不同服务的配置示例:

  • Python Flask:启动时指定主机地址
    app.run(host='127.0.0.1', port=9000)
    
  • Node.js Express:监听本地地址
    app.listen(9000, '127.0.0.1', () => {
      console.log('Server running on 127.0.0.1:9000');
    });
    
  • Docker容器:仅将端口映射到本地回环,而非所有网卡
    docker run -p 127.0.0.1:9000:9000 your-image
    
  • 后端Nginx服务:修改listen指令绑定本地地址
    server {
        listen 127.0.0.1:9000;
        # 其他配置...
    }
    

二、防火墙加固(可选但推荐)

即使服务已绑定本地地址,仍可通过防火墙关闭对外端口,彻底阻断外部访问端口的可能:

  • UFW(Ubuntu/Debian):
    sudo ufw deny 9000/tcp
    sudo ufw reload
    
  • Iptables:
    sudo iptables -A INPUT -p tcp --dport 9000 -j DROP
    sudo iptables-save | sudo tee /etc/iptables/rules.v4
    

三、Nginx反向代理配置(多路径路由 + Certbot HTTPS)

配置Nginx作为反向代理,实现基于路径的多服务路由,再通过Certbot配置HTTPS加密:

1. 基础HTTP配置(用于Certbot验证)

编辑Nginx配置文件(如/etc/nginx/sites-available/your-domain.conf):

server {
    listen 80;
    server_name your-domain.com; # 替换为你的域名

    # 路径路由到不同后端服务
    location /app1/ {
        proxy_pass http://127.0.0.1:9000/;
        # 传递必要的请求头,让后端获取真实客户端信息
        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;
    }

    location /app2/ {
        proxy_pass http://127.0.0.1:9001/;
        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;
    }

    # 允许Certbot进行域名验证
    location /.well-known/acme-challenge/ {
        root /var/www/html;
        allow all;
    }
}

启用配置并测试:

sudo ln -s /etc/nginx/sites-available/your-domain.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

2. 用Certbot配置HTTPS

安装Certbot并自动生成证书、配置HTTPS:

sudo apt update && sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com

执行后,Certbot会自动修改Nginx配置,添加HTTPS监听规则,并强制将HTTP请求跳转到HTTPS。

四、验证效果

  • 尝试直接访问公网IP:9000,应出现连接超时或拒绝访问
  • 通过https://your-domain.com/app1/或https://your-domain.com/app2/访问,应正常跳转至对应后端服务

内容的提问来源于stack exchange,提问作者Subhidh Agarwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:37:42