插件窝 干货文章 怎么在nginx中部署一个react项目

怎么在nginx中部署一个react项目

Nginx 配置 文件 React 841    来源:    2025-04-26

在 Nginx 中部署 React 项目(假设项目已构建完成)的步骤如下:


1. 构建 React 项目

在部署前,确保项目已通过 npm run build 生成静态文件(默认输出到 build/dist/ 目录):

npm install
npm run build

2. 配置 Nginx

2.1 上传文件

将构建后的静态文件(如 build/ 目录内容)上传到服务器目标路径,例如:

/var/www/my-react-app

2.2 修改 Nginx 配置

编辑 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;
    }
}

2.3 重启 Nginx

sudo nginx -t   # 测试配置语法
sudo systemctl restart nginx

3. 验证访问

通过浏览器访问 http://your-domain.com,确认页面正常加载。


常见问题解决

  1. 404 错误(React Router 路由失效)
    确保 location / 中包含 try_files $uri $uri/ /index.html

  2. 权限问题
    确保 Nginx 用户(如 www-data)有权访问静态文件:

    sudo chown -R www-data:www-data /var/www/my-react-app
    
  3. HTTPS 配置
    使用 Let's Encrypt 免费证书:

    sudo apt install certbot python3-certbot-nginx
    sudo certbot --nginx -d your-domain.com
    
  4. 性能优化
    启用 Gzip 压缩(在 Nginx 配置中添加):

    gzip on;
    gzip_types text/css application/javascript;
    

补充说明

  • 单页应用 (SPA) 配置:React 项目通常是 SPA,需通过 try_files 确保所有路径返回 index.html
  • 环境变量:构建时通过 .env 文件注入变量,而非运行时。

如需更复杂的代理或负载均衡,可进一步扩展 Nginx 配置。