LoginSignup
4
4

More than 5 years have passed since last update.

S3のRedirect Ruleを使ってみたメモ

Posted at

やりたかったこと

http://old.example.com/blog/post1 -> http://new.example.com/post1
http://old.example.com/blog/post2 -> http://new.example.com/post2
http://old.example.com.blog/ -> http://new.example.com/

のような子ディレクトリは一括リダイレクト、孫ディレクトリは個別リダイレクトという設定

ダメだったパターン

子ディレクトリのキーでリダイレクトかけると、孫も同じリダイレクトになる。
多分優先順位とかあるんだろうけど、調べる気力がなかったので誰か検証plz

<RoutingRules>
    <RoutingRule>
        <Condition>
            <KeyPrefixEquals>blog/post1</KeyPrefixEquals>
        </Condition>
        <Redirect>
            <HostName>new.example.com</HostName>
            <ReplaceKeyWith>post1/</ReplaceKeyWith>
            <HttpRedirectCode>301</HttpRedirectCode>
        </Redirect>
    </RoutingRule>
    <RoutingRule>
        <Condition>
            <KeyPrefixEquals>blog/</KeyPrefixEquals>
        </Condition>
        <Redirect>
            <HostName>new.example.com</HostName>
            <ReplaceKeyWith>/</ReplaceKeyWith>
            <HttpRedirectCode>301</HttpRedirectCode>
        </Redirect>
    </RoutingRule>
</RoutingRules>

対応

http://old.example.com.blog/ は実質http://old.example.com.blog/index.htmlを参照している。
なのでindex.htmlを削除して、S3からは404を返すようにした。
その上で以下のように404時のリダイレクトルールを設定する。

<RoutingRules>
    <RoutingRule>
        <Condition>
            <KeyPrefixEquals>blog/post1</KeyPrefixEquals>
        </Condition>
        <Redirect>
            <HostName>new.example.com</HostName>
            <ReplaceKeyWith>post1/</ReplaceKeyWith>
            <HttpRedirectCode>301</HttpRedirectCode>
        </Redirect>
    </RoutingRule>
    <RoutingRule>
        <Condition>
            <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <HostName>new.example.com</HostName>
            <ReplaceKeyWith>/</ReplaceKeyWith>
            <HttpRedirectCode>301</HttpRedirectCode>
        </Redirect>
    </RoutingRule>
</RoutingRules>

とりあえずこれで動く。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4