【问题标题】:Nginx rewriting pushstate static resources wont loadNginx重写pushstate静态资源不会加载
【发布时间】:2015-02-02 04:57:01
【问题描述】:

我正在尝试让 nginx 使用由 react-router 处理的基于 pushstate 的 uri。 一切正常,直到我尝试在二级 uri example.com/MyApp/users 上按 F5。

我的静态资源在example.com/MyApp/resources。 问题是,每当我尝试直接访问(或 F5)users 的视图时,nginx 都会尝试将我的资源加载到 example.com/MyApp/users/resources 中。

这是我的 nginx 配置文件:

location ~ ^/MyApp/ {
    try_files $uri /MyApp/index.html last;
}

我是 nginx 新手,所以我真的不知道一切是如何工作的......

编辑:

我将我的 conf 更改为:

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

现在访问example.com/MyApp/users 有效,但example.com/MyApp/users/ 无效。

【问题讨论】:

    标签: nginx pushstate react-router


    【解决方案1】:

    我认为你将不得不这样做:

    location ~ ^/MyApp/ {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ /index.html =404;
    }
    location ~ ^/MyApp/resources {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ /resources/index.html =404;
    }
    

    【讨论】:

      【解决方案2】:

      使用客户端应用路径:

      /
      /foo
      /foo/bar
      /foo/bar/baz
      /foo/bar/baz/123
      /tacos
      /tacos/123
      

      使用nginx配置:

      server {
          listen 80;
          server_name example.com;
          root /var/www/example.com;
      
          gzip_static on;
      
          location / {
            try_files $uri $uri/ /index.html;
          }
      
          # Attempt to load static files, if not found route to @rootfiles
          location ~ (.+)\.(html|json|txt|js|css|jpg|jpeg|gif|png|svg|ico|eot|otf|woff|woff2|ttf)$ {
            try_files $uri @rootfiles;
          }
      
          # Check for app route "directories" in the request uri and strip "directories"
          # from request, loading paths relative to root.
          location @rootfiles {
            rewrite ^/(?:foo/bar/baz|foo/bar|foo|tacos)/(.*) /$1 redirect;
          }
      }
      

      此配置将在诸如 example.com/foo/bar/baz/213123 之类的 pushState“目录”中工作,并将静态文件解析为相对路径(例如 js/app.jsexample.com/js/app.js 而不是 example.com/foo/bar/baz/js/app.js)。

      对于目录深度超出第一级的情况,例如/foo/bar/baz,请注意@rootfiles 指令中声明的目录顺序:可能的最长路径需要先行,然后是下一个较浅的路径/foo/bar 和最后/foo

      See this related answer to a similar question regarding Backbone.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-17
        • 1970-01-01
        • 2012-02-29
        • 2016-08-17
        • 2020-01-18
        • 1970-01-01
        • 2014-10-15
        • 2016-11-26
        相关资源
        最近更新 更多