Google Adsense広告をlocalhost(ローカル環境)で表示する
解決法
1. data-adtest属性の設定
<script
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxx"
crossorigin="anonymous"
></script>
<!-- xxx -->
<ins
class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxx"
data-ad-slot="xxx"
data-ad-format="auto"
data-full-width-responsive="true"
data-adtest="on"
></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
管理画面で上記のようなコードが発行されるが、data-adtest="on"
という属性と値を追加する。(本番環境では無効にする必要があるので、実際は"off"
とで動的に切り替える必要がある)
2. /etc/hostsでエイリアスを作成
sudo vim /etc/hosts
任意のホスト名で開発環境にアクセスできるよう、/etc/hosts
を編集する。
## # Host Database # # localhost is used to configure the loopback interface # when the system is booting. Do not change this entry. ## 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost
初期状態だと上記のような設定になっているはず。
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
127.0.0.1 dev.<YOUR_DOMAIN>
255.255.255.255 broadcasthost
::1 localhost
Google Adsenseに登録しているドメイン下もしくはそのサブドメイン下のサイトでないと広告は表示されない。そこで任意のホスト名でも開発環境にアクセスできるよう、エイリアスを追加する。
その後dev.<YOUR_DOMAIN>:<PORT>
にアクセスすると、無事アドセンス広告が表示された。