routing { // do 301 redirect to get rid of www for SEO benefits intercept(ApplicationCallPipeline.Features) { val host = this.context.request.host() val path = this.context.request.path() val port = this.context.request.port() if (host.contains("www.")) { this.context.response.status(HttpStatusCode.MovedPermanently) // detect protocol val protocolString = if (port == 443) { "https://" } else { "http://" } // detect if port should be included or not val portString = if (port == 80 || port == 443) { "" } else { ":$port" } // strip www from url val hostString = host.replace("www.", "") val newUrl = "$protocolString$hostString$portString$path" log.info("www-redirect to $newUrl") // redirect browser this.context.respondRedirect(url = newUrl, permanent = true) this.finish() } }