【问题标题】:How can I configure react-router to with nginx/cherrypy and my current reactjs app如何使用 nginx/cherrypy 和我当前的 reactjs 应用程序配置 react-router
【发布时间】:2016-07-18 04:32:28
【问题描述】:

我有一个由 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 像以前一样给了我应用程序。 但是理论上现在尝试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做不同的事情吗?

提前致谢。

【问题讨论】:

    标签: nginx reactjs react-router cherrypy


    【解决方案1】:

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

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

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

    location / {
        root /var/www;
        index index.html;
    
        try_files $uri $uri/ /index.html;
    }
    

    另外我修改了路由器的主要rednering:

    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>
    

    【讨论】:

    • index index.html 和 try_files index.html 为我工作!
    • 这个简洁的 try_files 路由器技巧可以在没有 nginx 网络服务器的谷歌存储桶中使用:) ackee.cz/blog/en/…
    猜你喜欢
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 2021-04-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    相关资源
    最近更新 更多