7 releases (breaking)

0.6.1 Mar 14, 2024
0.6.0 Feb 4, 2024
0.5.0 Jan 31, 2024
0.4.0 Jan 2, 2024
0.1.0 Aug 7, 2023

#4 in #allowed

Download history 40/week @ 2024-03-15 2/week @ 2024-03-22 11/week @ 2024-03-29 3/week @ 2024-04-05 120/week @ 2024-04-12

287 downloads per month

MIT license

510 lines


Project status & info:

License Crates Version Docs
License: MIT Crate Docs

Tower service which limits request from only hosts

Add as dependencies

Edit Cargo.toml file to add tower_allowed_hosts as dependencies

tower_allowed_hosts = "0.6.1"


To use non regex based hosts you can use

let tower_layer = tower_allowed_hosts::AllowedHostLayer::default().extend(&["".to_string()]);

If you need to use wildcard based host matching you need to enable wildcard feature for crate than you can use

let tower_layer = tower_allowed_hosts::AllowedHostLayer::default().extend_wildcard(&["127.0.0.*".to_string()]);

If you need to use regex based host matching you need to enable regex feature for crate than you can use

let tower_layer = tower_allowed_hosts::AllowedHostLayer::default().extend_regex(&[regex::Regex::new("^$")?]);

After creation of layer you can use layer in library which supports tower as component

For example to use tower allowed hosts in axum you also needs to add HandleErrorLayer so error gets handled properly

use axum::{
use tower::ServiceBuilder;
use tower_allowed_hosts::AllowedHostLayer;

fn router() -> Router {
    let handle_error_layer = HandleErrorLayer::new(handle_box_error);

    let allowed_hosts_layer = AllowedHostLayer::default()

     let layer = ServiceBuilder::new()


async fn handle_box_error(err: tower::BoxError) -> (StatusCode, String) {
    if err.is::<tower_allowed_hosts::error::Error>() {
        return (StatusCode::BAD_REQUEST, err.to_string());
    return (StatusCode::INTERNAL_SERVER_ERROR, "".to_string())

There is also extension added after successfully parsing allowed host and allowing host which can be access using tower_allowed_hosts::Host struct Extension


~52K SLoC