NewsDigest の短縮URL ndjust.in を経由させない

NewsDigest(株式会社JX通信社運営)という Android/iOS アプリからシェアしたリンクは、 ndjust.in で始まる転送用アドレスを経由するよう変換される。
この ndjust.in には Google Analytics が設定されているのみだが、気持ち悪いので直接元のページに移動するようにしよう。


ここではローカルで Apache を動かしている場合の設定方法を説明する。
まず /etc/hosts (Windows の場合は通常 C:/Windows/System32/drivers/etc/hosts) に次の記述を行い、 ndjust.in へのアクセスをすべてローカルの Apache へ向ける。

127.0.0.1	ndjust.in

次にバーチャルホストの設定を行うが、他のサイトや書籍を参考にしてほしい。その際、次のような設定を行い、mod_rewrite を用いてすべてのアクセスを /index.php へ向け、GET パラメータ _url に短縮 URL の ID を格納するようにする。

RewriteRule ^(.*)$ index.php?_url=$1 [L]

そして移動先ページの URL を取得するスクリプトは次のようになる。自動でのリダイレクトはしないようにした。

<?php
// コンソールでのテスト用
$path = isset($_GET['_url']) ? $_GET['_url'] : '6zMYUOOtsI';

$addresses = array(
	'54.192.233.19',
	'54.192.233.62',
	'54.192.233.93',
	'54.192.233.116',
	'54.192.233.173',
	'54.192.233.187',
	'54.192.233.191',
	'54.192.233.244',
);
$protocol = 'http://';
$host = 'ndjust.in';
$timeout = 5;

$headers = array(
	'Host: ' . $host,
	'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
	'Accept-Encoding: gzip,deflate',
	'Accept-Language: ja,en-us;q=0.7,en;q=0.3',
	'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0',
);

shuffle($addresses);
$url = $protocol . $addresses[0] . '/' . $path;

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);

$redirectTo = null;
if (preg_match('{<a href="(https?://.*?)" id="destination">}', $data, $matches)) {
	$redirectTo = $matches[1];
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>NewsDigest 経由のリダイレクト警告</title>
</head>
<body>
<?php if ($redirectTo) : ?>
<p>次の URL へリダイレクトしようとしています</p>
<p><a href="<?= htmlspecialchars($redirectTo) ?>"><?= htmlspecialchars($redirectTo) ?></a></p>
<?php else : ?>
<p>リダイレクト先が見つかりません</p>
<?php endif; ?>
</body>
</html>

以上で NewsDigest からシェアされたリンクに安心してアクセスできる。