如何配置react-router与nginx / cherrypy和我当前的reactjs应用程序

时间:2016-03-30 09:08:42

标签: nginx reactjs react-router cherrypy

我有一个工作网络应用程序由nginx提供服务,后端使用cherrypy,前端使用ReactJS。

应用程序增长了所以我想使用react-router来快速访问带有URL的页面。 例如,我希望my.domain.name/user将获得管理用户的应用程序中的部分。

我的单个index.html包含js包,如下所示: <script src="/js/bundle.js"></script>

直到现在,我的应用程序通过渲染AppMain开始。 现在,我创建了一个NoMatch类,并且我已将它们放入react-router中,如下所示:

ReactDOM.render((
    <Router history={browserHistory}>
        <Route path="/" component={AppMain}>
            <Route path="*" component={NoMatch}/>
        </Route>
    </Router>
), document.getElementById('main-central'));

尝试这个时效果很好。使用http://my.domain.name像以前一样给了我应用程序。 但是thoeritcally现在尝试http://my.domain.name/whatever应该渲染任何NoMatch渲染。但相反,我得到了nginx 404页面。

所以我认为需要一个nginx端配置,但可能不仅仅是(这就是我将整个故事带到上面的原因)。

Nginx配置(http部分)如下所示:

upstream app_servers {
    server 127.0.0.1:9988;
}

# Configuration for Nginx
server {

    location / {
        root /var/www;
        index index.html;
    }

    # Proxy connections to the application servers
    # app_servers
    location /api {
        proxy_pass         http://app_servers/api;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
    }
}

正如你所看到的,cherrypy正在获得所有/ api / *路径。

我在/ css,/ img等下面有静态内容,我想要正确使用它。

所以我需要一切不是静态的而不是/ api去js / bundle.js

如何在nginx中配置? 我是否需要以不同的方式在cherrypy或javascript中执行某些操作?

提前致谢。

1 个答案:

答案 0 :(得分:25)

找到我自己的答案......这是:

基本上nginx配置需要将网址重定向到/index.html(当然不是我的bundle.js)

在nginx conf中添加 try_files 可以解决这个问题:

location / {
    root /var/www;
    index index.html;

    try_files $uri $uri/ /index.html;
}

此外,我修改了路由器的主要更新:

ReactDOM.render(
    (<Router history={browserHistory}>
        <Route path="/" component={AppMainNewNav}>
            <Route path="users" component={UsersPage}/>
            <Route path="about" component={About}/>
        </Route>
        <Route path="*" component={NoMatch}/>
    </Router>)
    , document.getElementById('navbar'));

在AppMainNewNav render()中,我将导航修改为:

<nav>
    <ul role="nav">
        <li><Link to="/videos">Videos</Link></li>
        <li><Link to="/about">About</Link></li>
    </ul>
</nav>