在 Nginx 中部署 React 项目(假设项目已构建完成)的步骤如下:
在部署前,确保项目已通过 npm run build
生成静态文件(默认输出到 build/
或 dist/
目录):
npm install
npm run build
将构建后的静态文件(如 build/
目录内容)上传到服务器目标路径,例如:
/var/www/my-react-app
编辑 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/sites-available/default
):
server {
listen 80;
server_name your-domain.com; # 替换为域名或IP
root /var/www/my-react-app;
index index.html;
location / {
try_files $uri $uri/ /index.html; # 支持React Router
}
# 可选:静态文件缓存
location /static {
expires 1y;
add_header Cache-Control "public";
}
# 可选:API代理(如需后端接口)
location /api {
proxy_pass http://backend-server:port;
proxy_set_header Host $host;
}
}
sudo nginx -t # 测试配置语法
sudo systemctl restart nginx
通过浏览器访问 http://your-domain.com
,确认页面正常加载。
404 错误(React Router 路由失效)
确保 location /
中包含 try_files $uri $uri/ /index.html
。
权限问题
确保 Nginx 用户(如 www-data
)有权访问静态文件:
sudo chown -R www-data:www-data /var/www/my-react-app
HTTPS 配置
使用 Let's Encrypt 免费证书:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com
性能优化
启用 Gzip 压缩(在 Nginx 配置中添加):
gzip on;
gzip_types text/css application/javascript;
try_files
确保所有路径返回 index.html
。.env
文件注入变量,而非运行时。如需更复杂的代理或负载均衡,可进一步扩展 Nginx 配置。