在 CentOS 中配置 Node.js 反向代理,通常可以使用 Nginx 或 Apache 作为反向代理服务器。以下是使用 Nginx 和 Apache 配置反向代理的步骤:
安装 Nginx
sudo yum install epel-release sudo yum install nginx 启动并启用 Nginx
sudo systemctl start nginx sudo systemctl enable nginx 配置 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; } } 重启 Nginx
sudo systemctl restart nginx 安装 Apache 和 mod_proxy
sudo yum install httpd mod_proxy mod_proxy_http 启动并启用 Apache
sudo systemctl start httpd sudo systemctl enable httpd 配置 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> 重启 Apache
sudo systemctl restart httpd 无论使用 Nginx 还是 Apache,都可以通过访问你的域名来验证反向代理是否配置成功。如果一切正常,你应该能够看到 Node.js 应用的响应。
sudo firewall-cmd --permanent --zone=public --add-service=http sudo firewall-cmd --permanent --zone=public --add-service=https sudo firewall-cmd --reload 通过以上步骤,你可以在 CentOS 中成功配置 Node.js 反向代理。