WORKED EXAMPLE / ECMASCRIPT
HTTP and HTTPS URL regex
A conservative web URL check for HTTP(S), dotted hostnames, and an optional path, query, or fragment.
Pattern
^https?:\/\/(?:www\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z]{2,})+(?:[/?#][^\s]*)?$- Flavor
- JavaScript (ECMAScript)
- Flags
- Flags: i
What it does
This pattern is useful when a product deliberately accepts only ordinary public-looking HTTP and HTTPS URLs. It keeps the scheme explicit and prevents hostname labels from starting or ending with a hyphen.
Token-by-token explanation
^Starts matching at the beginning of the URL.
https?Requires http and permits one optional s for HTTPS.
:\/\/Requires the literal :// scheme separator.
(?:www\.)?Optionally accepts a leading www. hostname label.
[a-z0-9]Starts the first hostname label with a letter or digit.
(?:[a-z0-9-]*[a-z0-9])?Completes the first hostname label while ensuring a hyphen is not its final character.
(?:\.[a-z]{2,})+Requires one or more dotted alphabetic domain segments of at least two characters.
(?:[/?#][^\s]*)?Optionally accepts a path, query, or fragment beginning with /, ?, or # and containing no whitespace.
$Stops matching at the end of the URL.
Test strings
Matches
https://example.comhttp://www.docs.example.co.uk/path?q=regex#tokens
Does not match
ftp://example.comhttps://-example.com
Common mistakes
- Using a URL regex to prevent server-side request forgery instead of resolving and enforcing an explicit network allow-list.
- Making the scheme optional when the application requires an absolute navigable URL.
Limitations
- It intentionally excludes valid URLs such as localhost, IP-address hosts, ports, Unicode domains, and many percent-encoded or uncommon hostname forms; URL parsing and allow-listing are safer for security decisions.