1

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

MathKimRobin
  • 1,268
  • 3
  • 21
  • 52
  • It seems that [`path-to-regexp`](https://github.com/pillarjs/path-to-regexp) anchors the value you pass as a pattern by default. Try `'\??'` expression. Something like `.redirect('\??', '/', 301)`. – Wiktor Stribiżew Mar 21 '16 at 12:55
  • Don't seems to solve the bug... Have tried, doesn't work :( Thansk for your try of helping me – MathKimRobin Mar 21 '16 at 21:29

1 Answers1

2

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)
danneu
  • 9,244
  • 3
  • 35
  • 63