Regex for URL (http and https)

Use /^https?:\/\/[A-Za-z0-9.-]+\.[A-Za-z]{2,}(?::\d{1,5})?(?:\/[^\s]*)?$/ to check that a whole string is a valid for URL (http and https). Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^https?:\/\/[A-Za-z0-9.-]+\.[A-Za-z]{2,}(?::\d{1,5})?(?:\/[^\s]*)?$/
Open in Regex Tester
InputResult
https://example.com✓ Match
http://sub.example.co.uk:8080/path?q=1#top✓ Match
https://devpack.app/regex-tester✓ Match
example.com✗ No match
ftp://example.com✗ No match
https://localhost✗ No match
http://exa mple.com✗ No match

How the pattern works

PartMeaning
^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 false

Python

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.