Skip to main content

actix-web automatically upgrades connections to HTTP/2 if possible.

HTTP/2

TLS Negotiation Using ALPN​

When either of the rustls-0_23 or openssl features are enabled, HttpServer provides the bind_rustls_0_23() and bind_openssl() methods, respectively. See TLS / HTTPS for certificate setup. The example below uses rustls, the recommended option.

[dependencies]
actix-web = { version = "4", features = ["rustls-0_23"] }
rustls = "0.23"
rustls-pemfile = "2"
use std::{fs::File, io::BufReader};

use actix_web::{App, HttpRequest, HttpServer, Responder, web};

async fn index(_req: HttpRequest) -> impl Responder {
"Hello TLS World!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.unwrap();

let mut certs_file = BufReader::new(File::open("cert.pem").unwrap());
let mut key_file = BufReader::new(File::open("key.pem").unwrap());

// load TLS certs and key
// to create a self-signed temporary cert for testing:
// `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'`
let tls_certs = rustls_pemfile::certs(&mut certs_file)
.collect::<Result<Vec<_>, _>>()
.unwrap();
let tls_key = rustls_pemfile::pkcs8_private_keys(&mut key_file)
.next()
.unwrap()
.unwrap();

// set up TLS config options
let tls_config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(tls_certs, rustls::pki_types::PrivateKeyDer::Pkcs8(tls_key))
.unwrap();

HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind_rustls_0_23(("127.0.0.1", 8443), tls_config)?
.run()
.await
}

Check out the TLS examples for concrete example.

Cleartext HTTP/2 (H2C)​

When the http2 feature is enabled, HttpServer provides the bind_auto_h2c() and listen_auto_h2c() methods for accepting HTTP/1.x and HTTP/2 connections without TLS on the same port. These methods automatically select the protocol by reading the first few bytes of the connection.

Clients can use HTTP/2 with prior knowledge (RFC 7540 §3.4). Upgrades from HTTP/1.1 to HTTP/2 described in RFC 7540 §3.2 are not supported.