Execute CGI outside CGI-bin

November 28, 2006 / General Discussion

By default, many web servers (like Apache) are configured to run CGI scripts only inside the cgi-bin directory. While this is a good security practice, sometimes developers may want to execute CGI scripts from other folders for flexibility and easier application structure.

This guide explains how to enable CGI execution outside the default cgi-bin directory using a simple .htaccess configuration.

What is CGI and CGI-Bin?

  • CGI (Common Gateway Interface): A standard method that allows web servers to run external scripts (written in Perl, Python, etc.) and send dynamic content to users.

  • cgi-bin: The default directory where most servers store and execute CGI scripts.

By enabling CGI outside this directory, you can run scripts from custom folders useful for projects with unique directory structures.

Steps to Execute:

1. Create or Edit the .htaccess File

In the folder where you want to allow CGI, create (or edit) a file named .htaccess.

2. Add CGI Handler and Execution Options

Insert the following lines into .htaccess:

AddHandler cgi-script .pl .cgi
Options +ExecCGI

AddHandler cgi-script .pl .cgi >> tells Apache to treat .pl and .cgi files as executable scripts.

Options +ExecCGI >> enables execution of CGI scripts within that folder.

3. Set File Permissions

Ensure your script files have execute permission:

chmod 755 script.cgi
chmod 755 script.pl

4. Restart Apache (If Needed)

If changes don’t take effect immediately, restart Apache:

systemctl restart httpd

Best Practices:

  • Prioritize Security: Don’t allow CGI scripts to run outside trusted areas (like the cgi-bin folder) to avoid security risks.
  • Check Input: Make sure you clean and validate any user input to prevent attacks.
  • Limit Access: Use .htaccess or file permissions to control who can access important scripts.
  • Check for Errors: If scripts aren’t working, look at the Apache error logs for clues.