user3567004
user3567004

Reputation: 117

Redirecting Server Requests to /index.html for React/Angular SPA

Let's say I have a React or Angular app hosted at www.mywebsite.com/index.html with Apache serving the web app file. Inside the app, I have many routes defined such as /aboutus or /faq. But as we all know, there don't actually exist /aboutus.html or /faq.html files. These routes are built into the router in the web app.

So I'm wondering what happens if someone tries to access www.mywebsite.com/aboutus directly without first loading the web app at www.mywebsite.com/index.html. I've read online that what you have to do for this situation since you only have one actual file is redirect all http requests to /index.html. If you are using Apache, you have to configure it to redirect everything.

What I'm wondering is how do React/Angular routers know which route to load after the redirect. For example, if you go to www.mywebsite.com/aboutus, it redirects to www.mywebsite.com/index.html, and according to what I've read online, the React/Angular application will then be able to load the /aboutus route within the app after the redirect.

I would've imagined that the /aboutus gets lost in the redirect. If your server redirects to www.website.com/index.html, then you are at a different URL now and have lost the /aboutus. The web app gets loaded, but without the original target URL, it can't know where to go. How can this work?

Upvotes: 2

Views: 2257

Answers (2)

Andrei
Andrei

Reputation: 12021

server shouldn't redirect /aboutus to /index.html with 30X code response. instead it should response 200 index.html. in this case browser will load www...../aboutus link (it will get the same index.html as at .com/index.html path but just with another url) and FE famework scripts will handle the rest

Upvotes: 2

jsdeveloper
jsdeveloper

Reputation: 4045

and according to what I've read online, the React/Angular application will then be able to load the /aboutus route within the app after the redirect.

^^ This is true - what you have read is not lies at all. When the router code bootstraps, it checks the current url and sees if any matches, if it finds a match, it renders that route - otherwise it will use the fallback route (probably home or similar).

Upvotes: 0

Related Questions