2

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 :(

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The problem with your solution is it cannot solve the html5 state push feature. if I go example.com/v2/user/profile it will not work, because example.com/v2 is real path, and user/profile is just html5 router. thats why I use try_files so everything after /v2/ fall to v2/index.html
I misunderstood that you only want a 404 response if the URI contains a .. See revised answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.