Skip to main content

url_has_allowed_host_and_scheme

Return True if the url uses an allowed host and a safe scheme.

Always return False on an empty url.

If require_https is True, only 'https' will be considered a valid scheme, as opposed to 'http' and 'https' with the default, False.

Note: "True" doesn't entail that a URL is "safe". It may still be e.g. quoted incorrectly. Ensure to also use django.utils.encoding.iri_to_uri() on the path component of untrusted URLs.

def url_has_allowed_host_and_scheme(
url: string,
allowed_hosts: string | set | list,
require_https: boolean = False
) - > boolean

Return True if the url uses an allowed host and a safe scheme. Always return False on an empty url. If require_https is True, only 'https' will be considered a valid scheme, as opposed to 'http' and 'https' with the default, False.

Parameters

NameTypeDescription
urlstringThe URL string to be validated for safety.
allowed_hosts`stringset
require_httpsboolean = FalseIf True, restricts valid schemes to 'https' only; otherwise, both 'http' and 'https' are allowed.

Returns

TypeDescription
booleanTrue if the URL is considered safe based on the provided hosts and scheme requirements, otherwise False.