HTML URL 網址與路徑
URL (Uniform Resource Locator,統一資源定位器) 就是我們常說的「網址」,用來指向網路上某個資源的位置。在 HTML 中,當我們使用 <a> 建立超連結、用 <img> 嵌入圖片、或用 <link> 引入 CSS 等,都需要用 URL 來指定資源位置。
URL 的結構
一個完整的 URL 結構如下:
https://www.example.com:443/path/to/page.html?name=test&id=123#section1
\___/ \_____________/\__/\________________/\_______________/\_______/
| | | | | |
scheme host port path query fragment
各部分說明:
| 組成 | 說明 | 範例 |
|---|---|---|
| scheme | 通訊協議 | http, https, ftp, mailto |
| host | 主機名稱 (網域名稱或 IP) | www.example.com |
| port | 連接埠號碼 (可省略,使用預設) | 443, 80, 8080 |
| path | 資源路徑 | /path/to/page.html |
| query | 查詢參數 (用 ? 開頭) | ?name=test&id=123 |
| fragment | 頁面錨點 (用 # 開頭) | #section1 |
常見的 scheme:
http://- 一般網頁 (預設 port 80)https://- 加密安全網頁 (預設 port 443)ftp://- 檔案傳輸協議mailto:- 電子郵件tel:- 電話號碼
絕對路徑 vs 相對路徑
在 HTML 中指定 URL 時,我們可以使用絕對路徑或相對路徑。
絕對路徑 (Absolute URL)
絕對路徑是一個完整的 URL,包含 scheme 和 host,不管在哪個頁面都能正確指向同一個資源。
<a href="https://www.example.com/about.html">關於我們</a>
<img src="https://www.example.com/images/logo.png" />
絕對路徑適合用在:
- 連結到外部網站
- 需要確保在任何情況下都能正確指向資源
相對路徑 (Relative URL)
相對路徑是相對於當前頁面位置的路徑,不包含 scheme 和 host。
<a href="about.html">關於我們</a> <img src="images/logo.png" />
相對路徑適合用在:
- 連結到同一個網站內的資源
- 讓網站更容易搬遷到不同網域
相對路徑的寫法
假設目前頁面的 URL 是 https://www.example.com/products/phones/index.html
同目錄下的檔案
直接寫檔名:
<a href="iphone.html">iPhone</a>
結果會連到:https://www.example.com/products/phones/iphone.html
子目錄下的檔案
寫目錄名稱加檔名:
<a href="accessories/case.html">手機殼</a>
結果會連到:https://www.example.com/products/phones/accessories/case.html
上層目錄
用 ../ 表示往上一層目錄:
<a href="../tablets/ipad.html">iPad</a>
結果會連到:https://www.example.com/products/tablets/ipad.html
可以連續使用多個 ../ 往上多層:
<a href="../../index.html">回首頁</a>
結果會連到:https://www.example.com/index.html
從網站根目錄開始
用 / 開頭表示從網站根目錄開始:
<a href="/about.html">關於我們</a> <img src="/images/logo.png" />
不管目前頁面在哪,都會連到:
https://www.example.com/about.htmlhttps://www.example.com/images/logo.png
當前目錄
用 ./ 表示當前目錄 (通常可以省略):
<a href="./iphone.html">iPhone</a>
和直接寫 iphone.html 效果相同。
路徑寫法整理
| 寫法 | 說明 | 範例 |
|---|---|---|
file.html | 同目錄下的檔案 | about.html |
dir/file.html | 子目錄下的檔案 | images/logo.png |
../file.html | 上層目錄的檔案 | ../index.html |
../../file.html | 上兩層目錄的檔案 | ../../home.html |
/path/file.html | 從根目錄開始的路徑 | /assets/style.css |
./file.html | 當前目錄 (同 file.html) | ./about.html |
//host/path | 省略 scheme 的 URL | //cdn.example.com/lib.js |
// 開頭省略 scheme 的寫法,瀏覽器會自動使用當前頁面的 scheme (http 或 https),這種寫法常見於引入外部 CDN 資源。URL 編碼 (URL Encoding)
URL 中只能包含特定的字元,如果 URL 包含中文或特殊符號,需要進行 URL 編碼 (也叫做 Percent-encoding),將特殊字元轉換成 % 加上十六進位數字的格式。
舉個例子:
| 原始字元 | 編碼後 |
|---|---|
| 空格 | %20 |
! | %21 |
# | %23 |
% | %25 |
& | %26 |
? | %3F |
例如「關於我們」這幾個中文字,URL 編碼後會變成:
%E9%97%9C%E6%96%BC%E6%88%91%E5%80%91
現代瀏覽器會自動處理 URL 編碼,但在某些情況下你可能需要手動處理,可以使用 JavaScript 的 encodeURIComponent() 函式。