diff --git a/litestar/middleware/_utils.py b/litestar/middleware/_utils.py index 6a3cd6aec5..1f7a66ab7c 100644 --- a/litestar/middleware/_utils.py +++ b/litestar/middleware/_utils.py @@ -33,9 +33,10 @@ def build_exclude_path_pattern( try: pattern = re.compile("|".join(exclude)) if isinstance(exclude, list) else re.compile(exclude) - if pattern.match("/"): + if pattern.match("/") and exclude != "^/$": warn_middleware_excluded_on_all_routes(pattern, middleware_cls=middleware_cls) return pattern + except re.error as e: # pragma: no cover raise ImproperlyConfiguredException( "Unable to compile exclude patterns for middleware. Please make sure you passed a valid regular expression." diff --git a/tests/unit/test_middleware/test_base_middleware.py b/tests/unit/test_middleware/test_base_middleware.py index 33ab1092f9..b3c403f6e3 100644 --- a/tests/unit/test_middleware/test_base_middleware.py +++ b/tests/unit/test_middleware/test_base_middleware.py @@ -124,7 +124,7 @@ def third_handler() -> dict: assert "test" in response.headers -@pytest.mark.parametrize("excludes", ["/", ["/", "/foo"], "/*"]) +@pytest.mark.parametrize("excludes", ["/", ["/", "/foo"], "/*", "/.*"]) def test_exclude_by_pattern_warns_if_exclude_all(excludes: Union[str, List[str]]) -> None: class SubclassMiddleware(AbstractMiddleware): exclude = excludes