写好的前端页面npm build 之后放到httpd、tomcat的静态文件夹下之后,直接访问example.com,点击链接、按钮可以正常使用,但是刷新或直接输入url则报出404。
本人解决了404问题之后,可正常访问类似example.com/component的页面,但是类似example.com/component/othercomponent 多层路径 无法正常显示,方法在文末
问题原因:httpServer将你输入的url “example.com/component” 识别成了component目录,导致404。
解决办法:
- tomcat
最简单的办法,在WEB-INF/web.xml中添加,原理是将所有404的请求转发到index.html。
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
- httpd
在httpd.conf中启用RewriteEngine,将请求转发给index.html。
<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>
example.com/component/othercomponent 无法正常显示
example.com/component/othercomponent的页面可正确打开html(即不会404),但是页面无内容。
原因是项目中的js资源都是通过相对路径加载,Rewrite对此造成影响,解决方法是在index.html的
<header>
中添加<base href="/">
即可解决
参考:
https://gist.github.com/alexsasharegan/173878f9d67055bfef63449fa7136042
https://gkedge.gitbooks.io/react-router-in-the-real/content/apache.html