A URL (Uniform Resource Locator) is a string that uniquely identifies a resource on a network. Understanding URL structure and knowing how to parse URLs correctly are critical for web development, scraping, redirects, and integrations. This article covers URL components according to RFC 3986, encoding, parsing in JavaScript and Python, common errors, and tools for analysis.
For a quick URL breakdown, use the URL Parser on reChecker.
URL structure according to RFC 3986
The RFC 3986 standard defines the general form of a URL:
scheme:[//authority]path[?query][#fragment]Full example:
https://user:pass@example.com:443/path/to/page?key=value&foo=bar#sectionURL components
| Component | Description | Example |
|---|---|---|
| scheme (protocol) | Access protocol | https:, http:, ftp: |
| authority | Host, port, credentials | //example.com:443 |
| userinfo | Username and password (rarely used) | user:pass@ |
| host | Domain or IP address | example.com, 192.168.1.1 |
| port | Port (optional) | :443, :3000 |
| path | Path to the resource | /path/to/page |
| query | Query parameters | ?key=value&foo=bar |
| fragment | Anchor (part of a page) | #section |
Scheme (protocol)
Specifies how to access a resource. Common schemes include:
http:— HTTPhttps:— HTTPS (HTTP over TLS)ftp:— FTPmailto:— emailfile:— local file
The protocol ends with a colon. After //, the authority begins (for http/https).
Authority (host and port)
The authority includes the host and, optionally, the port. For HTTP, port 80 is omitted; for HTTPS, port 443 is omitted.
https://example.com → хост example.com, порт 443 (по умолчанию)
http://localhost:3000 → хост localhost, порт 3000
https://sub.example.com:8443 → хост sub.example.com, порт 8443Path
The path identifies a resource on the server. It starts with /. Segments are separated by slashes.
/path/to/page
/api/v1/users
/An empty path, or no path after the domain, is usually treated as /.
Query string
Parameters after ? in the format key=value, separated by &.
?q=search&page=1&lang=ruThe characters =, &, ?, # have special meanings. Values containing spaces, Cyrillic characters, or special characters must be encoded (percent-encoding).
Fragment (hash)
The fragment points to part of a document (an anchor). It is not sent to the server; it is handled by the client.
#section-2
#topURI, URL, and URN
URI (Uniform Resource Identifier) is the general term for resource identifiers. A URL is a subset of URIs that specifies a location and access method. A URN (Uniform Resource Name) identifies a resource by name without specifying its location (for example, urn:isbn:0451450523). Web development most often involves URLs; the terms URL and URI are often used interchangeably.
URL encoding (percent-encoding)
Characters outside the A-Za-z0-9-_.~ set and reserved characters :/?#[]@!$&'()*+,;= in certain positions are encoded as %XX, where XX is the hexadecimal code for a byte in UTF-8.
| Character | Encoding |
|---|---|
| Space | %20 or + (in form data) |
| Cyrillic «П» | %D0%9F (UTF-8) |
& | %26 |
= | %3D |
When a URL is parsed, the browser and server automatically decode its values. When constructing a URL manually, encode parameters using encodeURIComponent (JavaScript) or urllib.parse.quote (Python).
Absolute and relative URLs
Absolute URL
Contains a scheme and authority. A complete link to a resource.
https://example.com/page
http://localhost:3000/apiRelative URL
Relative to the current document or base URL.
| URL | Base URL | Result |
|---|---|---|
page | https://example.com/ | https://example.com/page |
/page | https://example.com/path/ | https://example.com/page |
../page | https://example.com/a/b/ | https://example.com/a/page |
?q=1 | https://example.com/ | https://example.com/?q=1 |
Parsing relative URLs requires a base URL for resolution. In JavaScript, new URL(path, base) handles this.
Parsing URLs in JavaScript
URL constructor
The modern API is the URL constructor:
const url = new URL('https://example.com/path?key=value#hash');
url.protocol; // "https:"
url.hostname; // "example.com"
url.port; // ""
url.pathname; // "/path"
url.search; // "?key=value"
url.hash; // "#hash"
url.origin; // "https://example.com"
url.href; // полный URLURLSearchParams for query strings
const url = new URL('https://example.com/search?q=hello&page=2');
url.searchParams.get('q'); // "hello"
url.searchParams.get('page'); // "2"
url.searchParams.get('missing'); // null
url.searchParams.forEach((value, key) => {
console.log(key, value);
});
// q hello
// page 2Resolving relative URLs
const base = 'https://example.com/path/';
const relative = '../other?q=1';
const resolved = new URL(relative, base);
// "https://example.com/other?q=1"Modifying parameters
const url = new URL('https://example.com/page?q=old');
url.searchParams.set('q', 'new');
url.searchParams.set('page', '1');
url.searchParams.delete('oldParam');
url.href; // "https://example.com/page?q=new&page=1"Parsing URLs in Python
urllib.parse
The standard library urllib.parse:
from urllib.parse import urlparse, parse_qs
url = 'https://example.com/path?key=value&foo=bar#section'
parsed = urlparse(url)
parsed.scheme # 'https'
parsed.netloc # 'example.com'
parsed.path # '/path'
parsed.query # 'key=value&foo=bar'
parsed.fragment # 'section'Parsing query strings
from urllib.parse import parse_qs, parse_qsl
query = 'key=value&foo=bar&foo=baz'
parse_qs(query) # {'key': ['value'], 'foo': ['bar', 'baz']}
parse_qsl(query) # [('key', 'value'), ('foo', 'bar'), ('foo', 'baz')]Building URLs
from urllib.parse import urlunparse, urlencode
components = ('https', 'example.com', '/path', '', 'key=value', '')
urlunparse(components) # 'https://example.com/path?key=value'
params = {'q': 'поиск', 'page': 1}
urlencode(params) # 'q=%D0%BF%D0%BE%D0%B8%D1%81%D0%BA&page=1'Resolving relative URLs
from urllib.parse import urljoin
base = 'https://example.com/path/'
urljoin(base, '../other?q=1') # 'https://example.com/other?q=1'Common parsing errors
Ignoring errors
An invalid URL raises an exception. Handle errors:
try {
const url = new URL(input);
// работа с url
} catch {
// некорректный URL
}Manual parsing with regex
Regular expressions do not handle all URL edge cases well (encoding, non-standard schemes, IPv6). Use built-in parsers.
Incorrect parameter encoding
Encode values when adding parameters:
// Неправильно
const url = `https://example.com/search?q=${userInput}`;
// Правильно
const url = `https://example.com/search?q=${encodeURIComponent(userInput)}`;Confusing encodeURI and encodeURIComponent
encodeURI— for a complete URL; does not encode;/?:@&=+$,#encodeURIComponent— for parameter values; encodes almost everything
Always use encodeURIComponent for query parameters.
Double encoding
If a value is already encoded, encoding it again will corrupt the data. Check the source.
reChecker URL Parser
The URL Parser service on reChecker lets you:
- Break a URL down into components: protocol, host, port, path, query string, and hash
- Get a table of query string parameters with their keys and values
- Check whether a URL is valid
- View the encoded and decoded forms
The tool is suitable for:
- Developers — debugging URLs and checking their structure
- SEO specialists — analyzing parameters in page URLs
- Testers — checking that generated links are correct
Paste a URL into the field and click “Analyze” — the results appear in a table breaking down each component. URLs with Cyrillic characters, parameters, and fragments are supported.
Practical scenarios
Extracting a domain from a link
const url = new URL('https://sub.example.com/path?q=1');
const domain = url.hostname; // "sub.example.com"Adding a parameter to the current URL
const url = new URL(window.location.href);
url.searchParams.set('utm_source', 'newsletter');
window.history.replaceState({}, '', url);Checking whether a link is internal
const link = new URL(href, window.location.origin);
const isInternal = link.origin === window.location.origin;Parsing UTM tags
const url = new URL(pageUrl);
const utm = {
source: url.searchParams.get('utm_source'),
medium: url.searchParams.get('utm_medium'),
campaign: url.searchParams.get('utm_campaign'),
};Special cases
IPv6: URLs with an IPv6 address enclose the host in square brackets: http://[::1]:8080/. The URL constructor and urllib.parse handle this format correctly.
Empty path: The URL https://example.com has a path of / (the root). When parsed, pathname returns /.
Multiple ?: In a query string, only the first ? separates the path and query. The character ? in a parameter value is encoded as %3F.
Empty values: The parameter key= has an empty value. URLSearchParams.get('key') returns '', not null.
Security and validation
When accepting URLs from users (forms, APIs), validation is necessary:
- Protocol: Allow only
http:andhttps:for web links to preventjavascript:ordata:injection - Host: Check that the domain does not point to internal resources (SSRF)
- Length: URLs that are too long can cause problems on the server or in logs
function isSafeUrl(href) {
try {
const url = new URL(href);
return ['http:', 'https:'].includes(url.protocol);
} catch {
return false;
}
}FAQ
What is RFC 3986?
RFC 3986 is a standard that defines URI syntax (with URLs as a subset). It describes the scheme, authority, path, query, and fragment, as well as encoding rules and relative reference resolution.
What is the difference between a path and a query string?
The path (/path/to/page) identifies a resource on the server. The query string (?key=value) passes additional request parameters. A path is usually stable for a given type of resource; the query changes depending on the parameters (filters, pagination, UTM).
How should I parse a query string with multiple values for the same key?
In JavaScript, URLSearchParams.getAll('key') returns an array of all values. In Python, parse_qs returns a dictionary in which each key maps to a list of values.
Why is the fragment (hash) not sent to the server?
The fragment is intended for client-side navigation within a document (anchors). The browser does not include it in the HTTP request. The server receives the URL without the part after #.
Which tool should I use to parse a URL?
reChecker URL Parser is a free online tool for breaking URLs down into components. It shows the protocol, host, port, path, query string parameters, and hash in a convenient table. It supports URLs with Cyrillic characters and displays their encoded/decoded forms. To encode and decode parameters, use reChecker URL Encoder.