apache - 使用 Apache 反向代理时 React-router url 不匹配

标签 apache express reactjs react-router mod-proxy

我正在尝试在 Apache 中设置反向代理来提供 React/Redux/webpack 包。我有一个 Express 服务器文件,为我的静态文件和 index.html 提供服务,如下所示:

const express = require('express');
const path = require('path');

const app = express();
const port = process.env.PORT || 3000;

app.use(express.static('./dist'));
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

我的 apache 配置如下所示:

<VirtualHost *:80>
  ProxyRequests off
  ProxyPass "/foo/" "http://localhost:8777/"
  ProxyPassReverse "/foo/" "http://localhost:8777/"
</VirtualHost>

现在,当导航到 example.com/foo 时,我的 index.html 和 webpack 包已正确提供,但 React 路由器会抛出错误,指出 /foo/ 与任何路由不匹配。显然,这是因为 /foo 是该应用程序的代理位置,而 React 路由器不会(也不应该)考虑生产中使用的代理路径。

如何设置 Apache,以便当请求发送到 localhost:8777 时,Apache 不会传递 /foo 路径?换句话说,如何设置 proxypass 以便将对 example.com/foo/bar 的请求转换为对服务器上的 localhost:8777/bar 的请求,然后返回给客户端,就好像它来自 example.com/foo/bar?

最佳答案

我的团队也遇到了类似的问题,他们解决这个问题的方法是使用 RewriteRule 和强制重定向 [R],然后让 Apache Proxy pass 捕获它。所以也许你可以尝试一下:

<VirtualHost *:80> ProxyRequests off RewriteRule ^/foo/bar/& /bar/ [R] ProxyPass "/bar/" "http://localhost:8777/" ProxyPassReverse "/bar/" "http://localhost:8777/" </VirtualHost>

我不是 Apache 配置方面的专家,因此您可能需要自己尝试一下 RewriteRule ( https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule )。但是,我相信上述内容可能只是您问题的一部分的答案:

how do you setup the proxypass so that a request to example.com/foo/bar is transformed to a request to localhost:8777/bar on the server

但我对此不太确定,抱歉:

then returned to the client as if it came from example.com/foo/bar?

希望其中一些能有所帮助。

关于apache - 使用 Apache 反向代理时 React-router url 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37421774/

相关文章:

java - HTTP 状态 404 – 在 rest api 响应中未找到错误

apache - 为什么可以从apache访问我的根目录?

javascript - 发送后出现错误 "can' t 设置 header ”

php - Apache 错误中的 rApache 模块

php - 单个网络服务器上的 PyPy + PHP

node.js - 当 Content-Type 为 text/csv 时 Sails.js 正文内容

node.js - 如何在 Node.js 的同一个文件中使用 ES6 导入和 CommonJS 导入

reactjs - 如何测试包含在 withRouter 中的 React 组件的回调?

javascript - mapStateToProps 赋值的最佳实践

reactjs - 如何更改material-ui slider 的拇指图标