温馨提示×

如何在 CentOS 中配置 Node.js 反向代理

小樊
72
2025-04-10 14:57:06
栏目: 编程语言

在 CentOS 中配置 Node.js 反向代理,通常可以使用 Nginx 或 Apache 作为反向代理服务器。以下是使用 Nginx 和 Apache 配置反向代理的步骤:

使用 Nginx 配置反向代理

  1. 安装 Nginx

    sudo yum install epel-release sudo yum install nginx 
  2. 启动并启用 Nginx

    sudo systemctl start nginx sudo systemctl enable nginx 
  3. 配置 Nginx 反向代理 编辑 Nginx 配置文件,通常位于 /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf

    sudo vi /etc/nginx/conf.d/default.conf 

    server 块中添加以下内容:

    server { listen 80; server_name yourdomain.com; location / { proxy_pass http://localhost:3000; # Node.js 应用的地址和端口 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; } } 
  4. 重启 Nginx

    sudo systemctl restart nginx 

使用 Apache 配置反向代理

  1. 安装 Apache 和 mod_proxy

    sudo yum install httpd mod_proxy mod_proxy_http 
  2. 启动并启用 Apache

    sudo systemctl start httpd sudo systemctl enable httpd 
  3. 配置 Apache 反向代理 编辑 Apache 配置文件,通常位于 /etc/httpd/conf/httpd.conf/etc/httpd/conf.d/yourdomain.conf

    sudo vi /etc/httpd/conf.d/yourdomain.conf 

    VirtualHost 块中添加以下内容:

    <VirtualHost *:80> ServerName yourdomain.com ProxyPass / http://localhost:3000/ ProxyPassReverse / http://localhost:3000/ ErrorLog /var/log/httpd/yourdomain-error.log CustomLog /var/log/httpd/yourdomain-access.log combined </VirtualHost> 
  4. 重启 Apache

    sudo systemctl restart httpd 

验证配置

无论使用 Nginx 还是 Apache,都可以通过访问你的域名来验证反向代理是否配置成功。如果一切正常,你应该能够看到 Node.js 应用的响应。

注意事项

  • 确保防火墙允许 HTTP 和 HTTPS 流量。
    sudo firewall-cmd --permanent --zone=public --add-service=http sudo firewall-cmd --permanent --zone=public --add-service=https sudo firewall-cmd --reload 
  • 如果使用的是 HTTPS,请确保配置 SSL 证书并相应地调整 Nginx 或 Apache 的配置文件。

通过以上步骤,你可以在 CentOS 中成功配置 Node.js 反向代理。

0