0

I am learning ReactJS and while creating a test app, I faced a problem. I am using .htaccess to redirect all invalid URLs to index.html for further processing. But something keeps breaking every time I enter an URL with more than one slash in it.

How to Replicate

.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:

(I am transpiling using Babel in a Gulp build. For test purposes, you can transpile online at 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')
)

So, when visiting http://localhost/anything it works fine. But, if I go to http://localhost/anything/something or http://localhost/anything/something/else then it breaks. The server still returns index.html by the way which gets loaded in the browser fine.

Am I doing something wrong?

1 Answer 1

1

Could possibly be a combination of several small issues, but have a look in your network tab to see if there's any problems loading. From your example app.js seems to be loading relatively and is not handled inside the rewrite. Try make all the links to assets absolute, i.e. /app.js

Sign up to request clarification or add additional context in comments.

1 Comment

That worked like a charm! I checked the network tab and you were right. The assets being served by relative paths were not being affected by rewrite. I'll try and learn more about the hows and whys of it. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.