1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FacebookでシェアするOGP画像を動的に書き換える

Posted at

Facebookでもシェアするぞ

以前書いたTwitterのogpに関わる話に続けて書こうと思ってた話を。
最近の若い子はFacebook使ってないらしいですが…シェアするっていうとtw,fb,insta,line辺りが主流かと認識してますがどうなんでしょうね。

おさらい

Twitterではパラメータをぶら下げて.htaccessでクローラ判定して〜って流れでした。
同様にFacebookもそれで行けるやろって思って組み込もうとした矢先、コードが以下のようになってたわけです。

<a href="https://www.facebook.com/sharer/sharer.php?u=https://tebasaki.mushamusha.jp?chicken=broiler" target="_blank">

あれれ〜おかしいぞ〜?なんですよね。
クエリにクエリが付いたURLを設定しちゃってるのでイミフな状況が生まれてるんです。
これではうまく動かないのでどうしたものやらと小一時間悩みました。

で考えたのが以下

<a href="https://www.facebook.com/sharer/sharer.php?u=https://tebasaki.mushamusha.jp/broiler/" target="_blank">

パラメータを一つの階層にしてしまえ!
で、最後の文字列を.htaccess側でパラメータにしてリダイレクトしてしまいしょう。


<IfModule mod_rewrite.c>
	RewriteEngine on
	RewriteCond %{HTTP_USER_AGENT} (facebookexternalhit/[0-9]|Twitterbot)
	RewriteCond %{REQUEST_URI} !(^/ogp.php)
	RewriteRule ^(.*)/$ ogp.php?chicken=$1 [L]
</IfModule>

受け側の動き

ogp.phpはもはや説明要らんと思いますがこんな感じです。

ogp.php
<?php
	$chicken = htmlspecialchars($_GET["chicken"],ENT_QUOTES);
	$ogpUrl = "https://tebasaki.mushamusha.jp/".$chicken."/ogp.png";

おわり。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?