如何为 React 路由设置 apache 服务器? [英] How to setup apache server for React route?
问题描述
我的 React 应用程序在本地开发服务器上运行良好,但是当我将生产就绪文件直接转储到 Apache 的 htdocs 目录时它不起作用:
I have my react app running great on my local dev server but it did not work when I dump my production ready files straight into Apache's htdocs directory:
这是我所拥有的:
/var/www/index.html
/var/www/bundle.js
我有
DocumentRoot /var/www
在/etc/apache2/sites-available/000-default.conf中
in /etc/apache2/sites-available/000-default.conf
事实是
1).当我访问 http://...com/ 时,将我路由到登录页面
2).点击链接后
The fact is that
1). when I access http://...com/ that routed me to Login page
2). After I clicked a link
<Link to="main"><button>Log In</button></Link>
浏览器位置字段的内容变为:
the content in the browser location field become:
http://...com/main
3).现在,如果我重新加载这个 url (http://...com/main),我得到了
3). Now if I reload this url (http://...com/main), I got
The requested URL /main was not found on this server
我在 React 中的循环:
My rounting in React:
<Router history={browserHistory }>
<Route path="/" component={TopContainer}>
<IndexRoute component={Login} />
<Route path='main' component={MainContainer} />
</Route>
</Router>
我在 apache 配置中还缺少什么?
What else I am missing in the apache configuration?
谢谢
推荐答案
更改 VirtualHost 配置(通常位于 /etc/httpd/conf.d\vhosts.conf
) 通过添加以下 Rewrite* 行:
Change the VirtualHost configuration (typically found in /etc/httpd/conf.d\vhosts.conf
) by adding the following Rewrite* lines:
<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: not found
.
This tells Apache to serve any files that exist, but if they don't exist, just serve /index.html
rather than a 404: not found
.
Apache 参考:配置 Apache 虚拟主机
react-router
历史参考:配置您的服务器
感谢从这里窃取的完整答案
这篇关于如何为 React 路由设置 apache 服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!