Debian 10 Buster
Sponsored Link

Apache2 : Rubyスクリプトを利用する2019/08/01

 
CGI を有効にして Ruby スクリプトが利用できるように設定します。
[1] Ruby をインストールします。
root@www:~#
apt -y install ruby
[2] 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

[3] 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/ruby
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 http://localhost/cgi-bin/test_script

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

# 拡張子 cgi および rb を CGI として扱う

<Directory "/var/www/html/cgi-enabled">
    Options +ExecCGI
    AddHandler cgi-script .cgi .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:
  service apache2 reload
root@www:~#
systemctl restart apache2

[5] 設定したディレクトリで CGI テストページを作成して動作確認をします。以下のようなページが表示されれば OK です。
root@www:~#
vi /var/www/html/cgi-enabled/index.rb
#!/usr/bin/ruby

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

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

関連コンテンツ