def scheme(name: String): Directive0


Rejects a request if its Uri scheme does not match a given one.

The scheme directive can be used to match requests by their Uri scheme, only passing through requests that match the specified scheme and rejecting all others.

A typical use case for the scheme directive would be to reject requests coming in over http instead of https, or to redirect such requests to the matching https URI with a MovedPermanently.

For simply extracting the scheme name, see the extractScheme directive.


sourceimport akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.Location
import StatusCodes.MovedPermanently

val route =
    scheme("http") {
      extract(_.request.uri) { uri =>
        redirect(uri.copy(scheme = "https"), MovedPermanently)
    scheme("https") {
      complete(s"Safe and secure!")

// tests:
Get("") ~> route ~> check {
  status shouldEqual MovedPermanently
  header[Location] shouldEqual Some(Location(Uri("")))

Get("") ~> route ~> check {
  responseAs[String] shouldEqual "Safe and secure!"
sourceimport static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.extract;
import static akka.http.javadsl.server.Directives.redirect;
import static akka.http.javadsl.server.Directives.scheme;

final Route route = concat(
  scheme("http", ()->
    extract((ctx) -> ctx.getRequest().getUri(), (uri)->
      redirect(uri.scheme("https"), StatusCodes.MOVED_PERMANENTLY)
  scheme("https", ()->
    complete("Safe and secure!")


  .assertEntity("Safe and secure!");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.