Enabling CGI on CentOS 6.5

It is my aim to have dynamic scripts executed when a user browses my homepage.

I am reaching this goal by enabling CGI for certain directories / virtual hosts.

My environment

Steps to configure

Assuming that you are familiar with apache httpd configurations stored at /etc/httpd/conf.d, a stub configuration file looks as follows:

        <Directory "/var/www/html/subdomain.domain.com">
           Options Indexes ExecCGI
           .... (other options) ...
        </Directory>

In essence, this really is enough.
Anyhow, you might have to enable the cgi-script handler by adding AddHandler cgi-script .cgi (somewhere) in your http configuration file.

Create a simple script

CGI Scripts (here: test.cgi) now essentially look as follows:

#!/bin/bash

# The script returns an HTML document.
# Any other mime-type works as well 😉 (e.g., images, ...)
echo "Content-type: text/html"
# blank line after the content type is required (http standard)
echo ""

# HTML content goes here.
echo "<html><body>"
echo "<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: center;\">"
echo "Test Page ( CGI Rocks! )"
echo "<br />This folders contents are:"
echo "<br />"
for i in *; do
        echo "$i<br />"
done
echo "</div>"
echo "</body></html>"

Note the first line (#!/bin/bash ) which triggers the interpretation of the contents by bash. The script essentially outputs plain Text in HTTP format, first mentioning the Content-type, followed by a newline, along with the contents.
For sure, using, e.g., Perl or Python is a smarter idea to this end…

Note that the file extension need to match the entries registered for the handler of the cgi-script hook in the previous step.

Leave a comment