redirectToTrailingSlashIfMissing

redirectToTrailingSlashIfMissing

Signature

Description

If the requested path does not end with a trailing / character, redirects to the same path followed by such trailing slash.

Redirects the HTTP Client to the same resource yet followed by a trailing /, in case the request did not contain it. When redirecting an HttpResponse with the given redirect response code (i.e. MovedPermanently or TemporaryRedirect etc.) as well as a simple HTML page containing a "click me to follow redirect" link to be used in case the client can not, or refuses to for security reasons, automatically follow redirects.

Please note that the inner paths MUST end with an explicit trailing slash (e.g. "things"./) for the re-directed-to route to match.

See also redirectToNoTrailingSlashIfPresent for the opposite behaviour.

Example

import akka.http.scaladsl.model.StatusCodes

val route =
  redirectToTrailingSlashIfMissing(StatusCodes.MovedPermanently) {
    path("foo"./) {
      // We require the explicit trailing slash in the path
      complete("OK")
    } ~
      path("bad-1") {
        // MISTAKE!
        // Missing `/` in path, causes this path to never match,
        // because it is inside a `redirectToTrailingSlashIfMissing`
        ???
      } ~
      path("bad-2/") {
        // MISTAKE!
        // / should be explicit as path element separator and not *in* the path element
        // So it should be: "bad-1" /
        ???
      }
  }

// tests:
// Redirected:
Get("/foo") ~> route ~> check {
  status shouldEqual StatusCodes.MovedPermanently

  // results in nice human readable message,
  // in case the redirect can't be followed automatically:
  responseAs[String] shouldEqual {
    "This and all future requests should be directed to " +
      "<a href=\"http://example.com/foo/\">this URI</a>."
  }
}

// Properly handled:
Get("/foo/") ~> route ~> check {
  status shouldEqual StatusCodes.OK
  responseAs[String] shouldEqual "OK"
}

// MISTAKE! will never match - reason explained in routes
Get("/bad-1/") ~> route ~> check {
  handled shouldEqual false
}

// MISTAKE! will never match - reason explained in routes
Get("/bad-2/") ~> route ~> check {
  handled shouldEqual false
}

See also redirectToNoTrailingSlashIfPresent which achieves the opposite - redirecting paths in case they do have a trailing slash.

Contents