Amplify Hosting でクエリパラメーターが保持されないパターンを試してみた
Setting up redirects and rewrites for an Amplify application - AWS Amplify Hosting
- If the original address includes a query string set to a specific value, Amplify doesn't forward query parameters. In this case, the redirect only applies to requests to the destination URL with the specified query value.
- If the destination address for the matching rule has query parameters, query parameters aren't forwarded. For example, if the destination address for the redirect is https://example-target.com?q=someParam, query parameters aren't passed through.
上記を試してみました。
アプリケーションの内容
index.js で取得したクエリパラメーターを index.html で表示するアプリケーションです。
コードは AI による生成です。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>クエリストリング表示サンプル</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
}
.result {
margin-top: 20px;
padding: 15px;
background-color: #f5f5f5;
border-radius: 5px;
}
.highlight {
color: #0066cc;
font-weight: bold;
}
</style>
</head>
<body>
<h1>クエリストリング表示サンプル</h1>
<p>このページは、URLのクエリストリングから <code>name</code> パラメータを取得して表示します。</p>
<p>例: <code>index.html?name=fuga</code></p>
<div class="result">
<p>クエリストリングの結果:</p>
<p>name = <span id="nameValue" class="highlight">取得中...</span></p>
</div>
<script src="index.js"></script>
</body>
</html>
// ページ読み込み時に実行
document.addEventListener("DOMContentLoaded", function () {
// URLからクエリストリングを取得
const urlParams = new URLSearchParams(window.location.search);
// 'name'パラメータの値を取得
const nameValue = urlParams.get("name");
// 結果を表示するための要素を取得
const nameElement = document.getElementById("nameValue");
// 値が存在する場合は表示、ない場合はメッセージを表示
if (nameValue) {
nameElement.textContent = nameValue;
} else {
nameElement.textContent = "(nameパラメータがありません)";
nameElement.style.color = "#cc0000";
}
});
パターン 1
元のアドレスに特定の値に設定されたクエリ文字列が含まれている場合
Amplify Hosting のリダイレクトルールは以下の通りです。
[
{
"source": "/<*>?name=test",
"status": "301",
"target": "/index.html"
}
]
上記ルールを設定後、Amplify Hosting のデフォルトドメインにクエリパラメーターを付与してアクセスします。
https://main.d2vakg0bdms0gn.amplifyapp.com/test?name=test
上記 URL にアクセス後、クエリパラメータを取得できずに index.html にリダイレクトされました。
https://main.d2vakg0bdms0gn.amplifyapp.com/index.html
パターン 2
マッチングルールの宛先アドレスにクエリパラメータがあるパターンです。
Amplify Hosting のリダイレクトルールは以下の通りです。
[
{
"source": "/<*>",
"status": "301",
"target": "/index.html?name=test"
}
]
上記ルールを設定後、Amplify Hosting のデフォルトドメインにクエリパラメーターを付与してアクセスします。
https://main.d2vakg0bdms0gn.amplifyapp.com/test?other=value
上記 URL にアクセス後、「?other=value」のクエリパラメータは消失し、以下の URL にリダイレクトしました。
https://main.d2vakg0bdms0gn.amplifyapp.com/index.html?name=test
クエリパラメータがない場合
クエリパラメータを付与せずにアクセスした場合、以下の挙動になりました。
- パターン 1: /test へアクセス → アクセス不可
- パターン 2: /test へアクセス → /index.html?name=test へリダイレクト
まとめ
今回は Amplify Hosting でクエリパラメーターが保持されないパターンを試してみました。
どなたかの参考になれば幸いです。
Discussion