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]
1 2 3 4 | #!/bin/bash echo -e "Content-type: text/html\n\n" echo "Welcome! to First CGI Script" |
Perl Script: [/usr/local/cgi-bin/myperl.cgi ]
1 2 3 4 | #!/usr/bin/perl 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.
1 2 3 4 5 6 7 8 9 10 11 | <VirtualHost *:80> ServerName www.example.com DocumentRoot /var/www/html ScriptAlias /cgi-bin/ "/usr/local/cgi-bin/" <Directory "/usr/local/cgi-bin/"> Require all granted Options +ExecCGI AddHandler cgi-script .cgi </Directory> </VirtualHost> |
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.
http://localhost/cgi-bin/myperl.cgi http://localhost/cgi-bin/mybash.cgi
2 Comments
1. The Perl-script is missing one newline.
2. For it to work a symbolic link to cgi.load had to be created in modules-enabled. Then a restart of Apache.
sudo ln -s /etc/apache2/mods-available/cgi.load /etc/apache2/mods-enabled/
sudo service apache2 restart
You were not mistaken