【问题标题】:NGINX - Refresh child route in SPA applicationNGINX - 在 SPA 应用程序中刷新子路由
【发布时间】:2020-04-16 13:26:09
【问题描述】:

我有一个 SPA 应用程序,用 ReactJS 编写。该应用程序有一个显示列表卡片的索引视图 (/myapp)。按下卡片会通过路由(/myapp/item/myapp/itemXX)重定向到新页面。当用户从索引访问时,应用程序工作正常。但是,在 /item 中刷新浏览器最终会出现 404 Not Found 错误。

服务器是NGINX,配置如下:

  # ...
  location /myapp {
    root /usr/share/nginx/html/;
        try_files $uri $uri/ /index.html;
        index index.html;
  }
  # ...

在我看到的日志文件中:

{
  "log": "2019/12/26 08:32:36 [error] 178#178: *3146 open() \"/etc/nginx/html/index.html\" failed (2: No such file or directory), client: 46.222.205.233, server: app.mydomain.com, request: \"GET /myapp/item/8?param=888 HTTP/2.0\", host: \"app.mydomain.com\"\n",
  "stream": "stderr",
  "time": "2019-12-26T08:32:36.253097755Z"
}

我已经尝试了几个位置规则但没有成功(location ^~ /myapp,为内部路由创建特定规则location /myapp/item)。

有什么帮助吗?谢谢!

【问题讨论】:

  • 嗨,这个帖子可能有用stackoverflow.com/questions/43555282/…
  • 感谢您的宝贵时间。我刚刚尝试过,但在我的情况下它不起作用。我看到的唯一不同是我的应用不在根目录 (/'') 中,而是在 '/myapp' 中。
  • 您是否尝试按照此答案中的说明设置您的根目录? stackoverflow.com/questions/45598779/…
  • 根据 /etc/nginx/html/index.html 不存在的日志,它看起来更像 - 你确定那个路径有一个文件并且它是你所期望的(React 的根文件)吗?跨度>
  • try_files 指令需要一个 URI 作为最后一个参数,因此您应该使用:try_files $uri $uri/ /myapp/index.html;

标签: reactjs nginx single-page-application


【解决方案1】:

我发现了这个问题,它总结了路由在服务器端和客户端的工作原理:

React-router urls don't work when refreshing or writing manually

适合我的解决方案是:

location /myapp {
  if (!-e $request_filename){
    rewrite ^(.*)$ /myapp/index.html break;
  }
}

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 2018-09-20
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多