外部のWebサイトで当方のサイトで掲載している画像を直接表示されてしまっています。
第三者のページの表示で当方のサーバー帯域を使われるのは問題があるので、対処したいです。
対処法を教えてください。
自分のサイトに掲載している画像が、外部の第三者サイトから直接リンクされる(いわゆる「ホットリンク」)ことがあります。
この状態を放置しておくと、自サイトのサーバー負荷が増大したり、意図しない文脈で画像が使用されるリスクが生じる可能性があります。
この記事では、IIS(Internet Information Services)を利用して外部からの画像アクセスを制御する手順を紹介します。
IIS URL Rewrite モジュールをインストールします。インストール手順はこちらの記事を参照してください。
対象としたいWebアプリケーションのディレクトリや、コンテンツのディレクトリに以下のWeb.Config
ファイルを配置します。
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Block Hotlinking" stopProcessing="true">
<match url=".*\.(jpg|jpeg|png|gif|webp)$" ignoreCase="true" />
<conditions>
<add input="{HTTP_REFERER}" pattern="^(https?://)?(www\.)?対象のドメイン\.com/" negate="true" />
<add input="{HTTP_REFERER}" pattern="^$" negate="true" />
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden" statusDescription="Hotlinking Forbidden" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
以下の設定で .jpg
.jpeg
.png
.gif
.webp
ファイルへのリクエストでリファラー(HTTP_REFERER)が対象のドメイン.com
以外からのアクセスの場合に
403 Forbidden(アクセス禁止) を返します。
<add input="{HTTP_REFERER}" pattern="^(https?://)?(www\.)?対象のドメイン\.com/" negate="true" />
リファラが空の場合も画像を表示します。
<add input="{HTTP_REFERER}" pattern="^$" negate="true" />
上記の設定は1つのドメインのみを制限していますが、デバッグ時や複数のサイトで対応する場合は以下の書式を利用します。
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Block Hotlinking" stopProcessing="true">
<match url=".*\.(jpg|jpeg|png|gif|webp)$" ignoreCase="true" />
<conditions>
<add input="{HTTP_REFERER}" pattern="^(https?://)?(www\.)?(対象のドメイン1\.com|対象のドメイン2\.net|対象のドメイン3\.jp|localhost)(:\d+)?(/|$)" negate="true" />
<add input="{HTTP_REFERER}" pattern="^$" negate="true" />
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden" statusDescription="Hotlinking Forbidden" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
からのアクセスを許可します。また、https://localhost:44387/
のようにポート番号がある場合のURLにも対応します。