1

I am trying to get nginx to work with a pushstate based uri handled by react-router. Everything works fine until I try to F5 on a second level uri example.com/MyApp/users.

My static resources are in example.com/MyApp/resources. The problem is that nginx is trying to load my resources in example.com/MyApp/users/resources whenever I try to access directly (or F5) the users's view.

Here is my nginx conf :

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

I am new to nginx so I don't really know how everything works...

EDIT :

I changed my conf to this:

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

Now accessing to example.com/MyApp/users works but example.com/MyApp/users/ doesn't.

2 Answers2

2

With client side app paths:

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

Use nginx configuration:

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

This configuration will work within a pushState "directory" such as example.com/foo/bar/baz/213123 and resolve static files at relative paths like js/app.js to example.com/js/app.js instead of example.com/foo/bar/baz/js/app.js.

For cases with directory depth beyond the first level such as /foo/bar/baz, note the order of the directories declared in the @rootfiles directive: the longest possible paths need to go first, followed by the next shallower path /foo/bar and finally /foo.

See this related answer to a similar question regarding Backbone.

Community
  • 1
  • 1
pxwise
  • 1,350
  • 15
  • 16
0

I think you will have to do something like this:

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;
}
michael_bitard
  • 3,613
  • 1
  • 24
  • 35