如何用Nginx、Capistrano和Passenger部署React前端+Rails API后端
Hey there! Let's walk through setting up your Nginx configuration to serve your React static files and proxy all /api requests to your Rails backend running on port 3001. This is a standard setup for full-stack React + Rails apps on EC2 Ubuntu, so we'll take it step by step.
1. 确认关键路径与Rails运行状态
First off, double-check the absolute path to your React app's build directory—for example, if you deployed your code to /var/www/my-app, your static files might live at:/var/www/my-app/client/build
Also, make sure your Rails app is bound to 0.0.0.0 (not just localhost) so Nginx can reach it. Start Rails with this command to ensure it's accessible:
rails server -p 3001 -b 0.0.0.0
2. 创建Nginx站点配置文件
Create a custom configuration file for your app in Nginx's sites-available directory. Let's name it my-app.conf (replace with your app's actual name):
sudo nano /etc/nginx/sites-available/my-app.conf
Paste in the following config, adjusting paths and server details to match your setup:
server { listen 80; server_name your-ec2-ip-or-domain.com; # 指向React静态文件目录 root /var/www/my-app/client/build; index index.html index.htm; # 处理React单页应用路由 location / { try_files $uri $uri/ /index.html; } # 代理所有/api请求到Rails后端 location /api { proxy_pass http://localhost:3001; 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; } }
Quick breakdown of what this does:
listen 80: Listens for incoming HTTP traffic on port 80root: Tells Nginx where to find your compiled React static filestry_files: Ensures React Router works for client-side routes—if a path doesn't match a static file, it servesindex.htmlso React can handle the routinglocation /api: Forwards all requests starting with/apito your Rails app, while passing along critical request headers so Rails knows the original request details
3. 启用配置并验证
Link your new config file to Nginx's sites-enabled directory to activate it:
sudo ln -s /etc/nginx/sites-available/my-app.conf /etc/nginx/sites-enabled/
Test for syntax errors in your configuration:
sudo nginx -t
If you see test is successful, restart Nginx to apply the changes:
sudo systemctl restart nginx
4. 额外的生产环境检查
- EC2安全组: Make sure your EC2 instance's security group allows inbound traffic on port 80 (HTTP). If you plan to add HTTPS later, also open port 443.
- Rails生产模式: Run Rails in production mode for better performance and security:
RAILS_ENV=production rails server -p 3001 -b 0.0.0.0 - HTTPS(推荐): For production, set up SSL with Let's Encrypt using Certbot—it will automatically configure Nginx for HTTPS and handle certificate renewal.
That's it! Your React app will be served from the build directory, and all /api requests will be forwarded to your Rails backend. If you hit issues, check Nginx's error logs at /var/log/nginx/error.log for troubleshooting clues.
内容的提问来源于stack exchange,提问作者John Hess

