distilagency / starward

:boom: ReactJS Wordpress Boilerplate
27 stars 9 forks source link

Redirect all non trailing slash page requests to the one with a trailing slash #135

Closed falconmick closed 6 years ago

falconmick commented 6 years ago

Check out how I did it in Sell My Shares, If I get time I will try to do myself, but all future projects needs this functionality (SEO request)

basically this www.some.com/link needs to be 301'd to www.some.com/link/ just make sure you can still access resources as www.some.com/assets/file.png/ is not going to work

SMS example: middleware.js

...
  match({routes, location: req.url}, (err, redirect, props) => {
    if (err) {
      res.status(500).json(err);
    } else if (redirect) {
      res.redirect(302, redirect.pathname + redirect.search);
    } else if (props) {
      // !!!!!!!!!! where the magic happens !!!!!!!!!!!
      const hasTrailingSlash = props.location.pathname.match(/(\/\s*$)|(\?.*$)/g);
      if (!hasTrailingSlash) {
        res.redirect(301, props.location.pathname.replace(/\s*$/g, '/'));
      }
      redisClient.get(props.location.pathname, (error, result) => {
        if (result) {
          res.status(200).send(result);
        } else if (props.routes[0].name === 'App') {
          const appFetch = fetchDataForApp(props)
          requestSuccess(appFetch)(props);
        } else {
          requestSuccess()(props);
        }
      });
    } else {
      res.sendStatus(404);
    }
  });
...
samlogan commented 6 years ago

@falconmick see this PR https://github.com/distilagency/starward/pull/137