scheme
Description
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.
Example
- Scala
-
source
import akka.http.scaladsl.model._ import akka.http.scaladsl.model.headers.Location import StatusCodes.MovedPermanently val route = concat( scheme("http") { extract(_.request.uri) { uri => redirect(uri.copy(scheme = "https"), MovedPermanently) } }, scheme("https") { complete(s"Safe and secure!") } ) // tests: Get("http://www.example.com/hello") ~> route ~> check { status shouldEqual MovedPermanently header[Location] shouldEqual Some(Location(Uri("https://www.example.com/hello"))) } Get("https://www.example.com/hello") ~> route ~> check { responseAs[String] shouldEqual "Safe and secure!" }
- Java
-
source
import 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!") ) ); testRoute(route).run(HttpRequest.GET("http://www.example.com/hello")) .assertStatusCode(StatusCodes.MOVED_PERMANENTLY) .assertHeaderExists(Location.create("https://www.example.com/hello")) ; testRoute(route).run(HttpRequest.GET("https://www.example.com/hello")) .assertEntity("Safe and secure!");