Ubuntu 20.04
Sponsored Link

Apache2 : CGI スクリプトを利用する2020/05/07

 
Apache httpd で CGI (Common Gateway Interface) スクリプトを利用する場合の設定です。
[1] CGI モジュールを有効にします。
root@www:~#
a2enmod cgid

Enabling module cgid.
To activate the new configuration, you need to run:
  systemctl restart apache2

root@www:~#
systemctl restart apache2

[2] CGI モジュールを有効にすると、デフォルトで [/usr/lib/cgi-bin] 配下が CGI 実行許可されます。
よって、例えば [/usr/lib/cgi-bin/index.cgi] スクリプトを作成して配置することで、[http://(Apache2 サーバー)/cgi-bin/index.cgi] へアクセス可能となります。 なお、当設定は [/usr/lib/cgi-bin] 配下のファイルを全て CGI と扱うため、CGI 以外のファイルは表示不可です。
# テストスクリプト作成

root@www:~#
cat > /usr/lib/cgi-bin/test_script <<'EOF'
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "Hello CGI\n";
EOF
root@www:~#
chmod 705 /usr/lib/cgi-bin/test_script
# 動作確認

root@www:~#
curl localhost/cgi-bin/test_script

Hello CGI
[3] 上記デフォルト以外のディレクトリで CGI の実行を許可する場合は以下のように設定します。
例として、[/var/www/html/cgi-enabled] 配下で CGI の実行を許可します。なお、CGI として扱う拡張子を指定しているため、html 等も配置可能です。
root@www:~#
vi /etc/apache2/conf-available/cgi-enabled.conf
# 新規作成

# [AddHandler cgi-script] に CGI として扱うファイルの拡張子を指定

<Directory "/var/www/html/cgi-enabled">
    Options +ExecCGI
    AddHandler cgi-script .cgi .pl .py .rb
</Directory>

root@www:~#
mkdir /var/www/html/cgi-enabled

root@www:~#
a2enconf cgi-enabled

Enabling conf cgi-enabled.
To activate the new configuration, you need to run:
  systemctl reload apache2

root@www:~#
systemctl restart apache2

[4] CGI を許可したディレクトリ配下に CGI テストページを作成して動作確認をします。 クライアント PC から Web ブラウザでテストページにアクセスして、正常にページが表示されれば OK です。
root@www:~#
vi /var/www/html/cgi-enabled/index.cgi
#!/usr/bin/python3

print("Content-type: text/html\n")
print("<html>\n<body>")
print("<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: center;\">")
print("CGI Script Test Page")
print("</div>")
print("</body>\n</html>")

root@www:~#
chmod 755 /var/www/html/cgi-enabled/index.cgi

関連コンテンツ