我的 React 应用程序在本地开发服务器上运行良好,但当我将生产就绪文件直接转储到 Apache 的 htdocs 目录时,它不起作用:
这是我所拥有的:
/var/www/index.html
/var/www/bundle.js
我有
DocumentRoot /var/www
在/etc/apache2/sites-available/000-default.conf 中
事实是
1)。当我访问http://...com/时这将我引导至登录页面
2)。单击链接后
<Link to="main"><button>Log In</button></Link>
浏览器位置字段中的内容变为:
http://...com/main
3).现在,如果我重新加载此网址( http://...com/main ),我会得到
The requested URL /main was not found on this server
我在 React 中的路由:
<Router history={browserHistory }>
<Route path="/" component={TopContainer}>
<IndexRoute component={Login} />
<Route path='main' component={MainContainer} />
</Route>
</Router>
我在 apache 配置中还缺少什么?
谢谢
最佳答案
通过添加以下 Rewrite* 行来更改 VirtualHost 配置(通常位于 /etc/httpd/conf.d\vhosts.conf
中):
<VirtualHost *:8080>
ServerName example.com
DocumentRoot /var/www/httpd/example.com
<Directory "/var/www/httpd/example.com">
...
RewriteEngine On
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
这告诉 Apache 提供任何存在的文件,但如果它们不存在,则仅提供 /index.html
而不是 404:未找到
。
Apache 引用:Configuring Apache Virtual Hosts
react-router
历史引用:Configuring Your Server
感谢从 here 窃取的完整答案
编辑:当前 apache 版本中的“On”需要大写
关于apache - 如何为 React 路由设置 apache 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44038456/