LoginSignup
2
2

Apache+CGIで全てのHTTPリクエストヘッダを出力する

Last updated at Posted at 2020-04-16

1. やりたいこと

Webサーバーが受け取るHTTPリクエストヘッダを確認したいため、全てのHTTPリクエストヘッダを出力するページを作ります。OSはCentOS7、CGIはpythonを使っています。

# cat /etc/redhat-release
CentOS Linux release 7.7.1908 (Core)

2. Apacheの導入

# yum install httpd
# httpd -v
Server version: Apache/2.4.6 (CentOS)
Server built:   Aug  8 2019 11:41:18

3. /etc/httpd/conf/httpd.confの編集

Apacheの設定ファイル(/etc/httpd/conf/httpd.conf)の編集

# SriptAliasの確認の確認
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

# /var/www/cgi-bin配下でCGIの実行を許可するように指定
# また、pyを拡張子に持つすべてのファイルを CGI プログラムとしてみなす
<Directory "/var/www/cgi-bin">
     AllowOverride None
     Options +ExecCGI
     Require all granted
     AddHandler cgi-script .py 
</Directory>

4. CGIスクリプトの配置

  • CGIスクリプトはこれを参考にした。出力が闇雲に並んでいてもわかりにくいので、名前をSortするように微修正している。
  • OriginサーバーはCentOS7なのでPython2.7ベースで記述。
  • Apacheのmod_cgiはHTTPリクエストヘッダを、環境変数に設定する際に以下の操作を行なっている。そのため、HTTP_というprefixを持つものだけを出力している。
    • HTTPヘッダー名を大文字変換する。
    • 「-」を「_」に変換する。
    • 「HTTP_」という接頭辞を付ける。
/var/www/cgi-bin/test.py
#!/usr/bin/env python

import os
print "Content-Type: text/html"
print "Cache-Control: no-cache"
print

print "<html><body>"
for headername, headervalue in sorted(os.environ.iteritems()):
    if headername.startswith("HTTP_"):
        print "{0} = {1}<br>".format(headername, headervalue)

print "</body></html>"
権限変更とApacheの再起動
# chmod 755 /var/www/cgi-bin/test.py
# systemctl restart httpd

5. 検証

curlでのテスト
# curl http://localhost/cgi-bin/test.py
<html><body>
HTTP_ACCEPT = */*<br>
HTTP_HOST = localhost<br>
HTTP_USER_AGENT = curl/7.29.0<br>
</body></html>

ブラウザでのテスト
image.png

2021/06/25補足

単にHTTPヘッダを出力したいアプリを作りたいだけなら、これで良かったかも。。。

# yum install -y httpd
# yum install -y php
# echo "<?php phpinfo(); ?>" > /var/www/html/test.php
# systemctl start httpd
2
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
2
2