Ad

How To Manage URL With Or Without ? And /

- 1 answer

In my Koa app, I've this kind of router :

app
    .use(router(app))
    .all('/', frontRoutes.home.index);

My problem is that :

  • mydomain.com
  • mydomain.com/
  • mydomain.com?

Are routed by the same route. It could be great but for Google it's not. Says that it's duplicate content. So I would like to redirect the first and third to the second. Like something to this :

app
    .use(router(app))
    .redirect('/\?', '/', 301)
    .redirect('', '/', 301)
    .all('/', frontRoutes.home.index);

Have tried some regexp without success. Already opened a Github issue but without answer too : https://github.com/alexmingoia/koa-router/issues/251 .

Thanks in advance for your help :)

Ad

Answer

There is no issue with koa-router. You can accomplish this with plain old middleware:

// Redirects "/hello/world/" to "/hello/world"
function removeTrailingSlash () {
  return function * (next) {
    if (this.path.length > 1 && this.path.endsWith('/')) {
      this.redirect(this.path.slice(0, this.path.length - 1))
      return
    }
    yield * next
  }
}

// Redirects "/hello/world?" to "/hello/world"
function removeQMark () {
  return function * (next) {
    if (this.path.search === '?') {
      this.redirect(this.path)
      return
    }
    yield * next
  }
}

// Middleware

app.use(removeTrailingSlash())
app.use(removeQMark())
app.use(router(app))

// Routes

app
  .all('/', frontRoutes.home.index)

app.listen(3000)
Ad
source: stackoverflow.com
Ad