HTML Uniform Resource Locators (URLs)
A Uniform Resource Locator (URL) is a reference to a web resource that specifies its location on a computer network and a mechanism for retrieving it. URLs are a fundamental aspect of web development as they are used to link to other web pages, resources, and files.
1. Basic URL Structure
A typical URL has the following structure:
protocol://hostname:port/path?query#fragment
Where:
- protocol: The scheme used to access the resource (e.g.,
http
,https
,ftp
). - hostname: The domain name or IP address of the server hosting the resource.
- port: The network port on the server (optional, default ports are 80 for HTTP and 443 for HTTPS).
- path: The specific location of the resource on the server.
- query: A string of key-value pairs used to pass data to the resource (optional).
- fragment: A reference to a specific part of the resource (optional).
2. Absolute URLs
An absolute URL contains the complete address to a resource, including the protocol and domain name.
Example:
Linking to an external website using an absolute URL:
<a href="https://www.example.com">Visit Example</a>
This will display as:
3. Relative URLs
A relative URL provides a path to a resource relative to the current document’s location. It is often used for linking to pages or resources within the same website.
Example:
Linking to another page in the same directory:
<a href="about.html">About Us</a>
This will display as:
4. Root-Relative URLs
A root-relative URL starts from the root directory of the website. It is useful for linking to resources regardless of the current document’s location.
Example:
Linking to a page from the root directory:
<a href="/contact.html">Contact Us</a>
This will display as:
5. Query Strings
Query strings are used to pass data to a resource via a URL. They are appended to the URL after a question mark (?
), with key-value pairs separated by an ampersand (&
).
Example:
Linking to a search page with query parameters:
<a href="search.html?query=html+urls">Search for HTML URLs</a>
This will display as:
6. URL Fragments
URL fragments, indicated by a hash symbol (#
), link to a specific part of a document, usually identified by an element’s id
attribute.
Example:
Linking to a specific section of a page:
<a href="#section2">Go to Section 2</a>
This will display as:
In the same document, you would have:
<h2 id="section2">Section 2</h2>
Conclusion
Understanding URLs and their components is essential for web development. Using absolute, relative, root-relative URLs, query strings, and fragments correctly ensures that users can navigate your site and access resources without issues.