LoginSignup
10
13

More than 5 years have passed since last update.

twitterカードの画像は絶対URIで指定しよう

Last updated at Posted at 2015-03-12

twitterカードには twitter:image というメタ情報の設定がある。
ここに画像のURLを指定しておくと、下記のようにURLツイート時に画像が展開されるようになる。

スクリーンショット 2015-03-13 0.10.24.png
※参考: https://dev.twitter.com/ja/cards/types/summary

問題

しかしながらこちらの設定には、普通に画像URLを渡すだけでいいものの、絶対URIで渡してあげないと画像を引っ張ってきてくれないというトラップがある。

例えばrailsとs3を使っている環境で、下記のような記述をしていた場合、 //s3 で始まる参照URIがレンダリングされるようになる。

meta name="twitter:image" content="#{image_url('hoge.png')}"

このような // で始まるURLは、 relative reference と呼ばれており、RFC3986 にて定義されている。
relative reference そのものの説明は下記の記事がコンパクトにまとまっていて分かりやすい。

If the browser is viewing that current page in through HTTPS, then it’ll request that asset with the HTTPS protocol, otherwise it’ll typically* request it with HTTP.
The Protocol-relative URL

このような参照URIを利用している場合、twitterは指定した画像を引っ張ってきてくれない。
よってhttpsから始まる絶対URIを用意しておく必要がある。

解決方法

上記問題を解決するために今回は、下記のようなヘルパーメソッドを作成した。

meta name="twitter:image" content="#{twitter_image_url}"
def twitter_image_url
  url = image_url('hoge.png')
  url = "https:#{url}" if url =~ /\A\/\/s3/
  url
end

これで image_url//s3 で始まるパスを返したとしても、 https: を文頭に付与し、絶対URIを返すようになった。

facebookの og:image は上記のような設定をしなくても、いい感じに空気読んで引っ張ってきてくれるので、はまりやすいところだと思う。

10
13
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
10
13