I am trying to issue a server side redirect for certain pages for SEO reasons. The problem I am trying to solve is that some of my pages will get index by google, so if they are deleted or taken offline we want to redirect them to a different page rather than showing 404. What is the best way to achieve such redirects with React Router on the server side(express.js)?
Asked
Active
Viewed 8,661 times
0
-
Keep a mapping for the same. Use a wrapper with the help of the mapping. – learner Jan 30 '18 at 11:59
-
@learner can you please expand? – MoPkoBot Jan 30 '18 at 12:05
-
Are you using React Router 4? – Gasim Jan 30 '18 at 13:19
3 Answers
0
You should have a component which should define routing rules, something like this:
<Router>
<Switch>
<Route path='/login' component= {LoginPage}/>
......
</Switch>
<Router>
All I am saying is that you should define a wrapper which define the redirect url:
var redirectToUrl = get url from your logic here;
var urlComponent = '';
if ( redirectToUrl )
{
urlComponent = <Redirect to={listing}/>;
}
Now add this to your url handling page:
<Router>
<div>
{urlComponent}
<Switch>
<Route path='/login' component= {LoginPage}/>
......
</Switch>
</div>
<Router>

learner
- 4,614
- 7
- 54
- 98
0
const redirect = (a,replace) => {
if(a.params.splat == "page1")
replace("/page2")
}
<Route path="*" ... onEnter={redirect}/>
in server.js
match(...,(error, redirectLocation, renderProps) => {
... else if (redirectLocation) { res.redirect(302,`${redirectLocation.pathname}${redirectLocation.search}`...);

Yousef Irman
- 109
- 4
-1
If you are using React Router 4, tou can add Redirect
component inside your Page component to redirect pages that are dead. Example: Let's say that component tried to fetch object from API but got an offline response and stored it in component state:
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
export default class PageComponent extends Component {
// ... other stuff
render() {
if (this.state.page_offline) {
return (<Redirect to="/some-page-for-offline-data" />);
}
return (...); // normal page render
}
}

Gasim
- 7,615
- 14
- 64
- 131
-
I am using React Router v3, and I am assuming this won't work with version 3 right? – MoPkoBot Jan 31 '18 at 07:38
-
No it won’t. Maybe this might help: https://stackoverflow.com/questions/35849884/how-to-make-redirect-inside-component-in-react-router#35853440 – Gasim Jan 31 '18 at 08:49