るいすのブログ

オタクエンジニアの雑記

Wordpressで記事新規追加時にレイアウトが崩れたりした時の対処法 Refused to apply inline style because it violates the following Content Security Policy directive


お久しぶりな記事 この夏はインターンに参加したり、今は静岡で合宿免許に来てます。 平日の休みと言えば三日間ぐらいしかありませんでしたが毎日充実してます。(家帰りてえ・・・)

 

合宿免許で暇だったので記事を書こうと思ってWordpressの新規追加をクリックしたところ テキストボックスは表示されるもそれ以外は適当に表示されていて頭を抱えました。

そんなときに便利なデベロッパーツールを使うとこんなエラーが! Refused to apply inline style because it violates the following Content Security Policy directive ~~~

エラーログにも書かれているように Content Security Policy を適切に設定しろってことですね。 ブラウザのセキュリティの一環でXSS対策、クリックジャッキング対策ができます。

ただもちろん弊害もあって、インラインのコードが実行されなくなります。 詳しくは知らないのでこちらのサイトが参考になるかと思います。

 

対処

magento2-nginx-configuration

アクセス制御を行う値をヘッダーに載せます。 nginxでの設定を記述しますがApacheでもできます。

/etc/nginx/conf.d/.confのserver {}に以下を記述します。

add_header Content-Security-Policy "default-src 'self'; 
     script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://www.google-analytics.com https://connect.facebook.net https://pagead2.googlesyndication.com https://ws.sharethis.com; 
     style-src 'self' 'unsafe-inline' https://fonts.googleapis.com 'self' https://themes.googleusercontent.com; 
     img-src 'self' https://ssl.google-analytics.com https://secure.gravatar.com https://d2fpdjmrf7iu2k.cloudfront.net https://www.google-analytics.com https://l.sharethis.com https://www.facebook.com https://stats.g.doubleclick.net data:; 
     child-src 'self' https://googleads.g.doubleclick.net https://staticxx.facebook.com; 
     object-src 'none'; 
     font-src 'self' https://fonts.gstatic.com data:;";

見にくいですけどとりあえずこのまんまコピペすればいいと思います。 値の意味に関してはこちらのサイトが参考になります。

 

%e3%82%b9%e3%82%af%e3%83%aa%e3%83%bc%e3%83%b3%e3%82%b7%e3%83%a7%e3%83%83%e3%83%88-2016-09-19-14-15-13 これでnginxを再起動してヘッダーを見ると変わっている箇所があると思います。 このContent-Security-Policyにあるサイトからのファイルは展開されるようになります。

Content-Security-Policy, X-XSS-Protection, X-Frame-OptionsとかWebサイトを公開する人は知っておかないとダメですね...徒歩歩