用Nginx对路由器html5 pushstae做出反应

时间:2017-04-11 21:59:04

标签: html5 nginx react-router

我有一个反应应用程序(使用react-router和html5 pushstate路由) 我希望http://example.com/v2作为服务我的新网站的基本路线

我使用这些nginx配置:

这样可以捕获/ v2并使用新的js文件

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

由于第一个位置块,即使404也将重定向到v2 / index.html,因此第二个位置的意图是使用扩展名处理uri,因此如果http://example.com/v2/user/profile/picture.jpg不存在,然后我仍然会得到正确的404资源未找到错误。

上面的代码显然不起作用,因为^〜具有更高的优先级然后〜。尝试2~但我得到try_files重定向循环:(

1 个答案:

答案 0 :(得分:2)

如您所知,将不会访问第二个位置块。此外,alias与正则表达式位置结合使用时更复杂。有关详情,请参阅this document

同时使用aliastry_files会导致问题(请参阅this long standing bug)。

尝试:

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

有关使用if的信息,请参阅this note