CGI stands for Common Gateway Interface are useful for creating dynamic content on the web page by transferring data from server to client. A CGI script can be written in any scripting language like Bash, java, C, Perl, Python, etc. Which can be easily executed by the webserver.
This article will help you to configure your own script as CGI scripts in Apache VirtualHost. We will use some test CGI scripts for example. Follow the below steps.
Step 1 – Create CGI Script
Create any test script in any scripting language. For this example, I am creating two scripts, one with the bash scripting and the other with Perl scripting.
Bash Script: [/usr/local/cgi-bin/mybash.cgi]
echo -e "Content-type: text/html\n\n"
echo "Welcome! to First CGI Script"
Perl Script: [/usr/local/cgi-bin/myperl.cgi ]
print "Content-type: text/html\n";
print "Welcome! to First CGI Script";
Now put your both scripts under scripts directory which can be created anywhere in the system. Make sure that it is accessible by Apache. For this example we have created both script under /usr/local/cgi-bin/ directory.
Step 2 – Configure Apache VirtualHost
Now edit Apache configuration file and go to defined VirtualHost. Add the following highlighted lines in the VirtualHost configuration.
ScriptAlias /cgi-bin/ "/usr/local/cgi-bin/"
Require all granted
AddHandler cgi-script .cgi
Save configuration file and restart Apache service.
Step 3 – Verify CGI Script
Now test your CGI scripts by opening URLs like below in your favorite web browser. You will show the text “Welcome! to First CGI Script” on your webpage.