redirect

Completes the request with a redirection response to a given targer URI and of a given redirection type (status code).

Signature

def redirect(uri: Uri, redirectionType: Redirection): StandardRoute 

Description

redirect is a convenience helper for completing the request with a redirection response. It is equivalent to this snippet relying on the complete directive:

complete {
  HttpResponse(
    status = redirectionType,
    headers = Location(uri) :: Nil,
    entity = redirectionType.htmlTemplate match {
      case ""        HttpEntity.Empty
      case template  HttpEntity(`text/html`, template format uri)
    })
}

Example

val route =
  pathPrefix("foo") {
    pathSingleSlash {
      complete("yes")
    } ~
    pathEnd {
      redirect("/foo/", StatusCodes.PermanentRedirect)
    }
  }

Get("/foo/") ~> route ~> check {
  responseAs[String] === "yes"
}

Get("/foo") ~> route ~> check {
  status === StatusCodes.PermanentRedirect
  responseAs[String] === """The request, and all future requests should be repeated using <a href="/foo/">this URI</a>."""
}