MST

星途 面试题库

面试题:Node.js HTTP 服务器与反向代理结合

描述如何将 Node.js 创建的 HTTP 服务器与 Nginx 反向代理结合使用,以提高安全性和性能。包括 Nginx 的配置步骤,以及 Node.js 服务器端需要做哪些调整以适应反向代理环境,同时说明在这种架构下如何处理 HTTPS 相关的配置。
27.2万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试

1. Nginx 配置步骤

  1. 安装 Nginx:根据不同操作系统,使用相应包管理器安装,如在 Ubuntu 上:
    sudo apt - get update
    sudo apt - get install nginx
    
  2. 配置反向代理:编辑 Nginx 配置文件(一般在 /etc/nginx/sites - available/default 或类似路径)。假设 Node.js 服务器运行在 localhost:3000
    server {
        listen 80;
        server_name your_domain.com;
    
        location / {
            proxy_pass http://localhost:3000;
            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;
        }
    }
    
  3. 启用配置:在 /etc/nginx/sites - enabled/ 目录下创建到上述配置文件的符号链接:
    sudo ln - s /etc/nginx/sites - available/default /etc/nginx/sites - enabled/
    
  4. 检查配置并重启 Nginx
    sudo nginx - t
    sudo systemctl restart nginx
    

2. Node.js 服务器端调整

  1. 处理代理头信息:如果使用 Express 框架,可以使用 express - proxy - headers 中间件来正确处理代理相关的头信息。对于原生 Node.js HTTP 服务器,可以在请求处理中获取并处理 X - Forwarded - For 等头信息。例如,在原生服务器中:
    const http = require('http');
    const server = http.createServer((req, res) => {
        const forwardedFor = req.headers['x - forwarded - for'];
        // 处理 forwardedFor 信息,如记录真实 IP 等
        res.end('Hello World');
    });
    server.listen(3000);
    

3. HTTPS 相关配置

  1. 获取 SSL 证书:可以从证书颁发机构(CA)购买,也可以使用 Let's Encrypt 免费获取。例如,使用 Certbot 获取证书:
    sudo apt - get install certbot python3 - certbot - nginx
    sudo certbot --nginx - d your_domain.com
    
  2. Nginx 配置 HTTPS:修改 Nginx 配置文件,添加 HTTPS 监听:
    server {
        listen 443 ssl;
        server_name your_domain.com;
    
        ssl_certificate /etc/letsencrypt/live/your_domain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/your_domain.com/privkey.pem;
    
        include /etc/nginx/snippets/ssl - params.conf;
    
        location / {
            proxy_pass http://localhost:3000;
            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;
        }
    }
    
  3. 重定向 HTTP 到 HTTPS:在 HTTP 监听的 server 块中添加重定向:
    server {
        listen 80;
        server_name your_domain.com;
        return 301 https://$server_name$request_uri;
    }
    
  4. Node.js 服务器不需要特殊处理 HTTPS:因为 Nginx 已经在前端处理了 HTTPS 连接,Node.js 服务器接收的是从 Nginx 反向代理过来的 HTTP 请求。