LoginSignup
8
12

More than 5 years have passed since last update.

[Apache httpd]複数ドメイン名のCORS対応ホワイトリスト設定

Posted at

前提1 経緯

  • Web上でCORS設定についての記事をあさると、All or Nothing な感じだったのが不満だった
    • 自社の要件としても不足していた

前提2 httpd バージョン

  • 2.4.4 以降
    • 本件で採用している req_novary が当該バージョンから採用されたため
    • 2.2.x のコードを見た限りでは採用を確認できていないので

参考URL

CORS対応ホワイトリスト用conf

以下のような形式で羅列していけばよい

  • Zone Apex な場合のFQDNに対して正規表現して対応する気力がなかったので割りきって別出しとした
    • 「hogeexample.comみたいなのが許可されてしまったら」と考えると精神衛生上よくない
    • 時間がなかった
  • プロトコル部を区別する場合には、https? を変更すればよいと思う
  • req_novary 行でマッチしたものに対して直接後方参照を利用する方法を見つけられなかった
    • のでわざわざ SetEnvIf ~~~ からの %{ORIGIN_URI}e の挿入を行っている
  • =~ m#regexp# は便利
    • =~ /regexp/ だと / がデリミタとなりどれだけエスケープしてもURLが入らずエラーとなった
    • 当初は -strmatch を利用していたが正規表現が使えてるのかよくわからず追うのをやめた
  • /etc/httpd/conf/cors.d 配下としたのは Include /etc/httpd/conf.d/*.conf に含めたくなかったから
    • 明示的にしたかっただけで本件において必須ではない
/etc/httpd/conf/cors.d/cors-pattern.conf
<If "req_novary('Origin') =~ m#^https?://example.com$#">
  SetEnvIf Origin "^(.*)$" ORIGIN_URI=$1
  Header set Access-Control-Allow-Origin "%{ORIGIN_URI}e" env=ORIGIN_URI
  Header set Access-Control-Allow-Credentials "true" 
</If>

<If "req_novary('Origin') =~ m#^https?://(.+).example.com$#">
  SetEnvIf Origin "^(.*)$" ORIGIN_URI=$1
  Header set Access-Control-Allow-Origin "%{ORIGIN_URI}e" env=ORIGIN_URI
  Header set Access-Control-Allow-Credentials "true" 
</If>

<If "req_novary('Origin') =~ m#^https?://(.+).example.net:8080$#">
  SetEnvIf Origin "^(.*)$" ORIGIN_URI=$1
  Header set Access-Control-Allow-Origin "%{ORIGIN_URI}e" env=ORIGIN_URI
  Header set Access-Control-Allow-Credentials "true" 
</If>

上記ホワイトリスト用confをIncludeすればよい

(例)/etc/httpd/conf/extra/httpd-ssl.conf
Include /etc/httpd/conf/cors.d/cors-pattern.conf

付録

ホワイトリスト出力用の雑なスクリプト
for FQDN_PORT in "example.com" "(.+).example.com" "(.+).example.net:8080" 
do
  echo " 
  <If \"req_novary('Origin') =~  m#https?://${FQDN_PORT}#\">
    SetEnvIf Origin "^\(.*\)\$" ORIGIN_URI=\$1
    Header set Access-Control-Allow-Origin \"%{ORIGIN_URI}e\" env=ORIGIN_URI
    Header set Access-Control-Allow-Credentials \"true\" 
  </If>
" 
done

  • ご指摘あればご遠慮なくお願いいたします。
    • 間違った知識を修正できるのでむしろうれしいです!
8
12
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
8
12