You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx静态部署Create-React-App构建的PWA:如何区分应用路由与静态资源?

问题描述

我通过Nginx静态部署一个使用Create-React-App构建的PWA,当前的Nginx location配置如下:

location / {
    root /etc/my_app/latest;
    index index.html;
    add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
    expires off;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept' always;
    allow all;
  }

目前的情况:

  • 访问https://my_domain_name_app/时,能正常找到/etc/my_app/latest/index.html文件;
  • 访问https://my_domain_name_app/assets/image.png时,能正常找到/etc/my_app/latest/assets/image.png文件;

但访问PWA的路由(如https://my_domain_name_app/login)时,Nginx会尝试在/etc/my_app/latest/下查找login文件,从而抛出404错误,而非加载应用的/login页面。请问如何配置Nginx以区分应用页面与静态资源?

解决方案

核心逻辑是让Nginx优先返回存在的静态资源,对不存在的路径,转发到index.html由React客户端路由处理。具体配置调整如下:

# 优先匹配并处理静态资源(如样式、脚本、图片等)
location ~* \.(html|css|js|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$ {
    root /etc/my_app/latest;
    # 静态资源设置长期缓存,提升加载性能
    add_header 'Cache-Control' 'public, max-age=31536000, immutable';
    expires 1y;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept' always;
    allow all;
}

# 处理SPA路由:当请求的文件/目录不存在时,返回index.html交由React路由解析
location / {
    root /etc/my_app/latest;
    index index.html;
    try_files $uri $uri/ /index.html;
    # 页面文件禁用缓存,确保用户获取最新版本
    add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
    expires off;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept' always;
    allow all;
}

配置说明

  1. 静态资源规则:通过正则匹配常见静态资源后缀,优先处理这类请求,直接返回对应文件,同时设置合理的缓存策略减少重复请求。
  2. SPA路由处理:try_files $uri $uri/ /index.html;指令会让Nginx依次尝试:请求的文件→请求的目录→返回index.html,确保所有自定义路由都能被React客户端路由接管。
  3. 缓存区分:静态资源设置长期缓存,页面文件禁用缓存,既优化性能又避免用户看到旧版本应用。

内容的提问来源于stack exchange,提问作者Bibas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:35:36