Yichz
Yichz

Reputation: 9681

react router html5 pushstae with Nginx

I have a react app (which uses react-router and html5 pushstate route) I would like http://example.com/v2 as base route to server my new website

I use these nginx config:

this to catch the /v2 and use the new js files

location ^~ /v2 {
        alias /usr/local/theapp/dist;
        try_files $uri $uri/ /v2/index.html;
        access_log /var/log/nginx/theapp/acces.web.log;
        error_log /var/log/nginx/theapp/error.web.log debug;
}

location ~ ^/(v2)/.+\..+$ {
        try_files $uri =404;
       alias /usr/local/theapp/dist;
       error_log /var/log/nginx/theapp/error.web.log debug;
}

Since with the first location block, even a 404 will be be redirect to v2/index.html, so The intention of the second location is to handle the uri with extension, so if http://example.com/v2/user/profile/picture.jpg does not exists, then I will still get the proper 404 resource not found error.

Above code obviously does not work, because ^~ has higher priority then ~. Tried with 2 ~ but I get try_files redirect loop :(

Upvotes: 2

Views: 391

Answers (1)

Richard Smith
Richard Smith

Reputation: 49762

As you note, the second location block will not be accessed. Also, the alias is more complex when used in conjunction with a regular expression location. See this document for more.

The use of alias and try_files together can cause problems (see this long standing bug).

Try:

location ^~ /v2 {
    alias /usr/local/theapp/dist;

    if (!-e $request_filename) {
        rewrite ^[^.]*$ /v2/index.html last;
    }

    access_log /var/log/nginx/theapp/acces.web.log;
    error_log /var/log/nginx/theapp/error.web.log debug;
}

See this note on the use of if.

Upvotes: 2

Related Questions