使用React和.htaccess

时间:2017-10-04 05:46:31

标签: .htaccess reactjs mod-rewrite

我正在学习ReactJS,在创建测试应用程序时,我遇到了一个问题。我正在使用.htaccess将所有无效网址重定向到index.html以进行进一步处理。但是每当我输入一个包含多个斜杠的URL时,就会出现问题。

如何复制

的.htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ / [L,QSA]

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test App</title>
</head>
<body>
    <div id="react-root"></div>
    <script src="app.js"></script>
</body>
</html>

app.jsx

(我正在使用Babel进行Gulp构建。出于测试目的,您可以在http://babeljs.io/repl/进行在线转换)

import React from 'react'
import ReactDOM from 'react-dom'

const TestPage = () => <span>{window.location.href}</span>

ReactDOM.render(
    <TestPage />
    ,document.getElementById('react-root')
)

因此,访问http://localhost/anything时,它可以正常工作。 但是,如果我转到http://localhost/anything/somethinghttp://localhost/anything/something/else,那么它会中断。服务器仍然按照在浏览器中加载的方式返回index.html

我做错了吗?

1 个答案:

答案 0 :(得分:1)

可能是几个小问题的组合,但请查看您的网络标签,看看是否存在加载问题。从您的示例app.js似乎相对加载,并不在重写内处理。尝试将所有资源链接设为绝对值,即/app.js