相対URLの解決方法

ブラウザがベースURLに対して相対URLをどのように解決するか、ドットセグメント(../と./)のルール、プロトコル相対URL、HTMLのbase要素を理解します。

Advanced

詳細な説明

相対URLの解決

相対URLは完全なスキームとホスト名を含まないURLです。ベースURLに対して解決され、絶対URLが生成されます。

相対参照の種類

ベースURLがhttps://example.com/blog/posts/page.htmlの場合:

相対URL 解決された絶対URL
other.html https://example.com/blog/posts/other.html
./other.html https://example.com/blog/posts/other.html
../index.html https://example.com/blog/index.html
/absolute/path https://example.com/absolute/path
//cdn.example.com/lib.js https://cdn.example.com/lib.js
?q=test https://example.com/blog/posts/page.html?q=test
#section https://example.com/blog/posts/page.html#section

URLコンストラクタの使用

// 第2引数がベースURL
new URL("../api/data", "https://example.com/app/page").href
// "https://example.com/api/data"

new URL("/assets/logo.png", "https://example.com/app/page").href
// "https://example.com/assets/logo.png"

<base>要素

HTMLの<base>タグはドキュメント内のすべての相対参照のベースURLを変更します:

<head>
  <base href="https://cdn.example.com/assets/">
</head>

プロトコル相対URL(非推奨)

//で始まるURLは現在のページのプロトコルを継承します。このパターンは現在非推奨とされています。常にhttps://を明示的に使用してください。

ユースケース

相対URL解決の理解は、ネストされたルート構造を持つWebサイトの構築、HTMLメールテンプレートの作業、リバースプロキシの設定、ドメイン間のコンテンツ移行において重要です。誤った相対パスはデプロイメント後の壊れた画像、欠落したスタイルシート、失敗したAPI呼び出しの一般的な原因です。

試してみる — URL Parser & Builder

フルツールを開く