How the pattern works
| Part | Meaning |
|---|---|
^https? | Starts with http, optionally followed by s |
:\/\/ | The literal :// (slashes escaped for JavaScript regex literals) |
[A-Za-z0-9.-]+ | Host name and subdomains |
\.[A-Za-z]{2,} | A dot and a top-level domain of two or more letters |
(?::\d{1,5})? | An optional port such as :8080 |
(?:\/[^\s]*)? | An optional path, query string and fragment — anything up to whitespace |
$ | End of the string |
Code examples
JavaScript
const re = /^https?:\/\/[A-Za-z0-9.-]+\.[A-Za-z]{2,}(?::\d{1,5})?(?:\/[^\s]*)?$/;
re.test(value); // true or falsePython
import re
bool(re.fullmatch(r'https?://[A-Za-z0-9.-]+\.[A-Za-z]{2,}(?::\d{1,5})?(?:/[^\s]*)?', value))PHP
preg_match('/^https?:\/\/[A-Za-z0-9.-]+\.[A-Za-z]{2,}(?::\d{1,5})?(?:\/[^\s]*)?$/', $value) === 1;
Notes and limitations
For validation in JavaScript, new URL(value) inside a try/catch is stricter and handles every edge case; use the regex when you also want to require http(s) and a public-looking domain. It rejects localhost and bare IP addresses on purpose.
Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool Frequently asked questions
What is the regex for URL (http and https)?
/^https?:\/\/[A-Za-z0-9.-]+\.[A-Za-z]{2,}(?::\d{1,5})?(?:\/[^\s]*)?$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: https://example.com, http://sub.example.co.uk:8080/path?q=1#top, https://devpack.app/regex-tester. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.