【问题标题】:React router with nginx用 Nginx 反应路由器
【发布时间】:2019-11-14 20:32:26
【问题描述】:

我在使用 react 路由器设置 nginx 时遇到了麻烦。我已经尝试了所有找到的建议解决方案,但似乎没有一个能涵盖我的用例。

这是我的文件系统上的一个结构,由 nginx 提供服务

/path/to/my/app
|- v1.0/index.html
`- v2.0/index.html

我在我的应用上部署了多个版本,每个版本都是一个独立的 React 应用。

然后还有一件事可以完成这个谜题。我的反应应用程序不在域根 URL(如 example.com/v1.0)上运行,而是在 example.com/my-app/v1.0 上运行。

所以我是这样配置nginx的

server {
  location ~ /my-app/([^/]+) { # capture version
    set $version $1; 
    root /path/to/my/app/$version  # directory where index.html is stored
    try_files $uri $uri/ /index.html
  }
}

访问example.com/my-app/v1.0 工作正常,但如果路径包含react 中的路由(example.com/my-app/v1.0/users),nginx 会返回404,因为它想提供一个文件/path/to/my/app/v1.0/users,而该文件显然不存在。

另外值得一提的是,我的应用程序仅在像 example.com/my-app/v1.0/ 而不像 example.com/my-app/v1.0/index.html 那样访问时才有效。后者没有配置任何路由。

【问题讨论】:

    标签: reactjs nginx react-router


    【解决方案1】:

    一种选择是使用带有前缀 locationalias,例如:

    location /my-app/ {
        alias /path/to/my/app/;
        if (-e $request_filename) { 
            rewrite ^(/my-app/[^/]+) $1/index.html last; 
        }
    }
    

    locationalias 指令的值都应该以/ 结尾,或者都不以/ 结尾。由于this issue,请避免使用try_filesalias。关于if的使用见this caution


    另一种选择是您的方法,但用正确的值替换 try_files 术语。例如:

    location ~ /my-app/(?<version>[^/]+)(?<suffix>/.*)?$ {
        root /path/to/my/app/$version;
        try_files $suffix $suffix/ /my-app/$version/index.html;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-12
      • 2017-09-07
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多