In computing, Common Gateway Interface (CGI) is an interface specification that enables web servers to execute an external program to process HTTP/S user requests.[1]

Such programs are often written in a scripting language and are commonly referred to as CGI scripts, but they may include compiled programs.[2]

A typical use case occurs when a web user submits a web form on a web page that uses CGI. The form's data is sent to the web server within an HTTP request with a URL denoting a CGI script. The web server then launches the CGI script in a new computer process, passing the form data to it. The output of the CGI script, usually in the form of HTML, is returned by the script to the Web server, and the server relays it back to the browser as its response to the browser's request.[3]

Developed in the early 1990s, CGI was the earliest common method available that allowed a web page to be interactive. Due to a necessity to run CGI scripts in a separate process every time the request comes in from a client various alternatives were developed.


The official CGI logo from the spec announcement

In 1993, the National Center for Supercomputing Applications (NCSA) team wrote the specification for calling command line executables on the www-talk mailing list.[4][5][6] The other Web server developers adopted it, and it has been a standard for Web servers ever since. A work group chaired by Ken Coar started in November 1997 to get the NCSA definition of CGI more formally defined.[7] This work resulted in RFC 3875, which specified CGI Version 1.1. Specifically mentioned in the RFC are the following contributors:[3]

Historically CGI programs were often written using the C programming language. RFC 3875 "The Common Gateway Interface (CGI)" partially defines CGI using C,[3] in saying that environment variables "are accessed by the C library routine getenv() or variable environ".

The name CGI comes from the early days of the Web, where webmasters wanted to connect legacy information systems such as databases to their Web servers. The CGI program was executed by the server that provided a common "gateway" between the Web server and the legacy information system.

Purpose of the CGI specification

Each Web server runs HTTP server software, which responds to requests from web browsers. Generally, the HTTP server has a directory (aka “folder”), which is designated as a document collection, that is, a set of files that can be sent to Web browsers connected to the server.[8] For example, if a web server has the fully-qualified domain name, and its document collection is stored at /usr/local/apache/htdocs/ in the local file system, then the web server will respond to a request for by sending to the browser a copy of the (previously-written) file /usr/local/apache/htdocs/index.html. Conventional terminology would refer to the directory /usr/local/apache/htdocs as the server’s document root, a term not to be confused with the root directory of the filesystem hierarchy on a UNIX-like server.

For pages constructed on the fly, the server software may defer requests to separate programs and relay the results to the requesting client (usually, a Web browser that displays the page to the end user). In the early days of the Web, such programs were usually small and written in a scripting language; hence, they were known as scripts.

Such programs usually require some additional information to be specified with the request. For instance, if Wikipedia were implemented as a script, one thing the script would need to know is whether the user is logged in and, if logged in, under which name. The content at the top of a Wikipedia page depends on this information. Accordingly, HTTP provides ways for browsers to pass such information to the server, e.g., as part of the URL. The server software must somehow then pass this information through to the script.

Conversely, upon returning, the script must provide all the information required by HTTP for a response to the request: the HTTP status of the request, the document content (if available), the document type (e.g. HTML, PDF, or plain text), et cetera.

Initially, there were no standardized methods for data exchange between a browser, the HTTP server with which it was communicating and the scripts on the sever that were expected to process the data and ultimately return a result to the browser. As a result, mutual incompatibilities existed between different HTTP server variants that undermined script portability.

Recognition of this problem led to the specification of how data exchange was to be carried out, resulting in the development of the Common Gateway Interface or CGI. Web page-generating programs invoked by server software that adheres to the CGI specification are known as CGI scripts, even though they may actually have been written in a non-script language, such as C.

The CGI specification was quickly adopted and continues to be supported by all well-known HTTP server packages, such as Apache, Microsoft IIS, and (with an extension) node.js-based servers.

An early use of CGI scripts was to process forms. In the beginning of HTML, HTML forms typically had an "action" attribute and a button designated as the "submit" button. When the submit button is pushed the URI specified in the "action" attribute would be sent to the server with the data from the form sent as a query string. If the "action" specifies a CGI script then the CGI script would be executed, the script in turn generating an HTML page.

Using CGI scripts

A Web server allows its owner to configure which URLs shall be handled by which CGI scripts.

This is usually done by marking a new directory within the document collection as containing CGI scripts – its name is often cgi-bin. For example, /usr/local/apache/htdocs/cgi-bin could be designated as a CGI directory on the Web server. When a Web browser requests a URL that points to a file within the CGI directory (e.g.,, then, instead of simply sending that file (/usr/local/apache/htdocs/cgi-bin/ to the Web browser, the HTTP server runs the specified script and passes the output of the script to the Web browser. That is, anything that the script sends to standard output is passed to the Web client instead of being shown on-screen in a terminal window.

HTTP data exchange with a script

As remarked above, the CGI specification defines how additional information passed with the request is passed to the script. For instance, if a slash and additional directory name(s) are appended to the URL immediately after the name of the script (in this example, /with/additional/path), then that path is stored in the PATH_INFO environment variable before the script is called.

If parameters are sent to the script via an HTTP GET request (a question mark appended to the URL, followed by param=value pairs; in the example, ?and=a&query=string), then those parameters are stored in the QUERY_STRING environment variable before the script is called.

If parameters are sent to the script via an HTTP POST request, they are passed to the script's standard input. The script can then read these environment variables or data from standard input and adapt to the Web browser's request.[9]


The following Perl program shows all the environment variables passed by the Web server:

#!/usr/bin/env perl


printenv — a CGI program that just prints its environment

print "Content-Type: text/plain\n\n";

foreach ( sort keys %ENV ) {
    print "$_=\"$ENV{$_}\"\n";

If a Web browser issues a request for the environment variables at, a 64-bit Windows 7 Web server running cygwin returns the following information:

DOCUMENT_ROOT="C:/Program Files (x86)/Apache Software Foundation/Apache2.4/htdocs"
HTTP_ACCEPT_ENCODING="gzip, deflate, br"
HTTP_USER_AGENT="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:67.0) Gecko/20100101 Firefox/67.0"
PATH_TRANSLATED="C:\Program Files (x86)\Apache Software Foundation\Apache2.4\htdocs\foo\bar"
SCRIPT_FILENAME="C:/Program Files (x86)/Apache Software Foundation/Apache2.4/cgi-bin/"
SERVER_ADMIN="(server admin's email address)"
SERVER_SOFTWARE="Apache/2.4.39 (Win32) PHP/7.3.7"

Some, but not all, of these variables are defined by the CGI standard. Some, such as PATH_INFO, QUERY_STRING, and the ones starting with HTTP_, pass information along from the HTTP request.

From the environment, it can be seen that the Web browser is Firefox running on a Windows 7 PC, the Web server is Apache running on a system that emulates Unix, and the CGI script is named cgi-bin/

The program could then generate any content, write that to standard output, and the Web server will transmit it to the browser.

The following are environment variables passed to CGI programs:

The program returns the result to the Web server in the form of standard output, beginning with a header and a blank line.

The header is encoded in the same way as an HTTP header and must include the MIME type of the document returned.[10] The headers, supplemented by the Web server, are generally forwarded with the response back to the user.

Here is a simple CGI program written in Python 3 along with the HTML that handles a simple addition problem.[11]


<!DOCTYPE html>
  <form action="add.cgi" method="POST">
     <legend>Enter two numbers to add</legend>
     <label>First Number: <input type="number" name="num1"></label><br/>
     <label>Second Number: <input type="number" name="num2"></label><br/>


#!/usr/bin/env python3

import cgi, cgitb

input_data = cgi.FieldStorage()

print("Content-Type: text/html") # HTML is following
print("")                        # Leave a blank line
print("<h1>Addition Results</h1>")
    num1 = int(input_data["num1"].value)
    num2 = int(input_data["num2"].value)
    print("<output>Sorry, the script cannot turn your inputs into numbers (integers).</output>")
    raise SystemExit(1)
print("<output>{0} + {1} = {2}</output>".format(num1, num2, num1 + num2))

This Python 3 CGI program gets the inputs from the HTML and adds the two numbers together.


A Web server that supports CGI can be configured to interpret a URL that it serves as a reference to a CGI script. A common convention is to have a cgi-bin/ directory at the base of the directory tree and treat all executable files within this directory (and no other, for security) as CGI scripts. Another popular convention is to use filename extensions; for instance, if CGI scripts are consistently given the extension .cgi, the Web server can be configured to interpret all such files as CGI scripts. While convenient, and required by many prepackaged scripts, it opens the server to attack if a remote user can upload executable code with the proper extension.

In the case of HTTP PUT or POSTs, the user-submitted data are provided to the program via the standard input. The Web server creates a subset of the environment variables passed to it and adds details pertinent to the HTTP environment.


CGI is often used to process input information from the user and produce the appropriate output. An example of a CGI program is one implementing a wiki. If the user agent requests the name of an entry, the Web server executes the CGI program. The CGI program retrieves the source of that entry's page (if one exists), transforms it into HTML, and prints the result. The Web server receives the output from the CGI program and transmits it to the user agent. Then if the user agent clicks the "Edit page" button, the CGI program populates an HTML textarea or other editing control with the page's contents. Finally if the user agent clicks the "Publish page" button, the CGI program transforms the updated HTML into the source of that entry's page and saves it.


CGI programs run, by default, in the security context of the Web server. When first introduced a number of example scripts were provided with the reference distributions of the NCSA, Apache and CERN Web servers to show how shell scripts or C programs could be coded to make use of the new CGI. One such example script was a CGI program called PHF that implemented a simple phone book.

In common with a number of other scripts at the time, this script made use of a function: escape_shell_cmd(). The function was supposed to sanitize its argument, which came from user input and then pass the input to the Unix shell, to be run in the security context of the Web server. The script did not correctly sanitize all input and allowed new lines to be passed to the shell, which effectively allowed multiple commands to be run. The results of these commands were then displayed on the Web server. If the security context of the Web server allowed it, malicious commands could be executed by attackers.

This was the first widespread example of a new type of Web based attack, where unsanitized data from Web users could lead to execution of code on a Web server. Because the example code was installed by default, attacks were widespread and led to a number of security advisories in early 1996.[12]


For each incoming HTTP request, a Web server creates a new CGI process for handling it and destroys the CGI process after the HTTP request has been handled. Creating and destroying a process can be expensive: consume CPU time and memory resources than the actual work of generating the output of the process, especially when the CGI program still needs to be interpreted by a virtual machine. For a high number of HTTP requests, the resulting workload can quickly overwhelm the Web server.

The overhead involved in CGI process creation and destruction can be reduced by the following techniques:

The optimal configuration for any Web application depends on application-specific details, amount of traffic, and complexity of the transaction; these trade-offs need to be analyzed to determine the best implementation for a given task and time budget. Web frameworks offer an alternative to using CGI scripts to interact with user agents.

See also


  1. ^ Robinson <>, David (2004). "The Common Gateway Interface (CGI) Version 1.1". doi:10.17487/RFC3875. Archived from the original on 8 March 2021. Retrieved 16 February 2021.
  2. ^ Robinson <>, David (2004). "The Common Gateway Interface (CGI) Version 1.1". doi:10.17487/RFC3875. Archived from the original on 11 February 2007. Retrieved 16 February 2021.
  3. ^ a b c Robinson, D.; Coar, K. (2004). "RFC3875: The Common Gateway Interface (CGI) Version 1.1". doi:10.17487/RFC3875. Archived from the original on 19 April 2021. Retrieved 25 February 2012. ((cite journal)): Cite journal requires |journal= (help)
  4. ^ McCool, Rob (November 14, 1993). "Server Scripts". www-talk (Mailing list). Retrieved 2019-05-15.
  5. ^ "The Common Gateway Interface". National Center for Supercomputing Applications (NCSA). Archived from the original on 27 January 2010.
  6. ^ "CGI: Common Gateway Interface". World Wide Web Consortium. Archived from the original on 19 December 2009. Retrieved 2019-05-15.
  7. ^ "Common Gateway Interface RFC Project Page". Archived from the original on 25 August 2013.
  8. ^ "Mapping URLs to Filesystem Locations Apache HTTP Server Version 2.2". Archived from the original on 15 July 2014. Retrieved 16 July 2014.
  9. ^ Nelson, Anne Fulcher, and Nelson, William Harris Morehead. (2001). Building Electronic Commerce with Web Database Constructions. Boston, MA: Addison Wesley.
  10. ^ "CGI Primer (Mirror at". Archived from the original on 6 October 2011. Retrieved 28 June 2011.
  11. ^ "Abacles HTML Forms". Archived from the original on 19 April 2016. Retrieved 6 April 2016.
  12. ^ "phf CGI Script fails to guard against newline characters". Software Engineering Institute CERT Coordination Center. Archived from the original on 28 July 2020. Retrieved 21 November 2019.
  13. ^ Enrico Marino (11 September 2018). Information Management in the Distributed Web (PDF) (phd). Roma Tre University. Archived (PDF) from the original on 12 February 2019. Retrieved 11 February 2019.