Skip to main content
ApacheCentOS

Executing CGI scripts on an Apache web server

By April 12, 2013September 12th, 2022No Comments

One thing you will certainly need to do with your Apache web server is being able to execute CGI scripts, server-side scripts, on the server. For this we will have to enable a few modules if we are to start, as ourselves, with a minimal httpd configuration. The three modules that we will add are:

  • mod_cgi.so : for CGI scripts execution
  • mod_alias.so : so we can house our scripts in anoahter location to the DocumentRoot for higher security
  • mod_mime.so : for file type associations , so we can asscoiate, in this case, .pl files with CGI

The modules.conf file should now be similar to this:

/etc/httpd/conf.d/modules.conf

		LoadModule authz_host_module modules/mod_authz_host.so
		LoadModule dir_module modules/mod_dir.so
		LoadModule info_module modules/mod_info.so
		LoadModule status_module modules/mod_status.so
		LoadModule cgi_module modules/mod_cgi.so
		LoadModule mime_module modules/mime_cgi.so
		LoadModule alias_module modules/alias_cgi.so

With this in place we are going to add some lines to the httpd.conf. We will want a ScriptAlias directive to we can ensure that our executable scripts can be kept separate from out main pages. The pages do no need the execute option but, of course, scripts will. In the directory block for the aliased directory we add in execute permission with Options +ExecCGI The httpd.conf will now look similar to this:

/etc/httpd/conf/httpd.conf

		Listen 0.0.0.0:80
		User apache
		Group apache
		ServerName www.example.com
		ErrorLog /var/log/httpd/error.log
		Include conf.d/modules.conf
		DirectoryIndex index.html
		DocumentRoot /var/www/html
		<Directory /var/www/html>
        	AllowOverride None
        	Order allow,deny
        	allow from 192.168.0.0/24
		</Directory>
		<Location /server-status>
		SetHandler server-status
		Order allow,deny
		Allow 192.168.0.199
		</Location>
		<Location /server-info>
		SetHandler server-info
		Order allow,deny
		Allow 192.168.0.199
		</Location>
		TypesConfig /etc/mime.types
		AddHandler cgi-script .pl
		ScriptAlias /cgi-bin/ /var/log/cgi-bin
		<Directory /var/log/cgi-bin/ >
		Options +ExecCGI
		</Directory>

So now that the server is up and running we can add, in this case, perl scripts into the directory, /var/log/cgi-bin. We will need to make sure they have an extension of .pl to match the association we created and we will need to make sure we have the execute permission in Linux added with chmod.

user.pl

		!/usr/bin/perl
		print "Content-type: text/plainnn";
		print "Hello worldn";

username.pl

		!/usr/bin/perl
		use CGI qw(:standard);
		my $username = param('username');
		print header;
		print start_html("My perl page");
		print h2("Hello $username");
		print p("This page was generated by perl");
		print end_html;