Common Gateway Interface

On this page 7

The Common Gateway Interface (CGI) is a protocol between a web server and an external program: for each matching HTTP request, the server starts a separate process, passes request data through environment variables and standard input, and returns whatever the program writes to standard output as the response. In web servers, CGI was the first general mechanism for generating dynamic content, and its conventions still shape FastCGI, WSGI and other gateway interfaces used on modern Servers.

CGI is defined in RFC 3875 (CGI/1.1), published in 2004 to document behavior that had been in use since 1993. It is language-neutral: a CGI program can be a shell script, a Perl or Python script, or a compiled C binary, as long as it follows the input and output contract.

How the Common Gateway Interface handles a request

A CGI request follows a fixed fork-and-exec lifecycle in which the server acts as a gateway between the network and a local program. The server first maps the URL to a script, usually through a configured directory such as /cgi-bin/ or a handler rule for a file extension, and then creates a new process for every request.

  1. The web server parses the HTTP request and selects the CGI script from the URL path.
  2. It builds a set of meta-variables such as REQUEST_METHOD, QUERY_STRING and CONTENT_LENGTH and places them in the process environment.
  3. It starts the program and pipes the request body (for example POST form data) to its standard input.
  4. The program writes response headers, a blank line and then the body to standard output.
  5. The server parses those headers, adds missing protocol details and sends the response to the client; the process then exits.

The program must emit at least one header, typically Content-Type, or a Location header for a redirect. A Status header lets the script choose the HTTP status code. In the non-parsed header (NPH) variant, the script writes the complete HTTP response itself and the server passes it through unchanged.

The following table lists the most important meta-variables that a CGI program reads to understand the request.

VariableContentsTypical use
REQUEST_METHODGET, POST, HEAD or another methodChoosing how to read input
QUERY_STRINGText after the question mark in the URLParsing search or filter parameters
CONTENT_LENGTHSize of the request body in bytesReading exactly that many bytes from standard input
CONTENT_TYPEMedia type of the bodyDetecting form or JSON encoding
PATH_INFOExtra path after the script nameBuilding clean, routed URLs
REMOTE_ADDRIP address of the client or proxyLogging and access decisions
HTTP_*Request headers, such as HTTP_USER_AGENTReading cookies and client details
Core CGI meta-variables

Performance cost of one process per request

The defining weakness of CGI is the per-request process startup. Creating a process, loading an interpreter, compiling the script and opening database connections can take from a few milliseconds for a small C binary to tens or hundreds of milliseconds for an interpreted application with many libraries, and all of that work is discarded when the process exits.

Because nothing persists between requests, CGI cannot keep connection pools, caches or loaded code in memory. Under concurrent load, each simultaneous request also occupies its own process, so memory consumption grows linearly with traffic and a traffic spike can exhaust process limits and RAM. These costs led to persistent alternatives that keep a worker alive and reuse it for many requests.

The table summarizes where the time goes in a typical interpreted CGI request.

StageCostAvoided by persistent workers
Process creationKernel fork and exec on every requestYes
Interpreter startupLoading the runtime and standard modulesYes
Application loadingImporting frameworks and parsing configurationYes
Database connectionTCP and authentication handshakeYes, through pooling
Actual request logicQueries and renderingNo
Sources of overhead in a CGI request

CGI compared with FastCGI, WSGI and modules

Later gateway interfaces keep the CGI variable model but change how the program lives. FastCGI runs long-lived worker processes that receive many requests over a socket; PHP-FPM is the best-known FastCGI process manager. WSGI and ASGI define in-process calling conventions for Python, served by tools such as Gunicorn, uWSGI and Uvicorn. Server modules such as mod_php embed the interpreter directly in the web server.

The comparison below shows how each approach trades isolation for speed.

ApproachProcess modelSpeedIsolation
CGINew process per requestLowVery high
FastCGIPersistent worker pool over a socketHighHigh
WSGI or ASGIPersistent Python application serverHighHigh
Embedded moduleInterpreter inside the server processHighLow
Reverse proxy to app serverSeparate HTTP service behind the serverHighHigh
Gateway approaches for dynamic content

Notably, WSGI deliberately reuses CGI names: its environ dictionary carries REQUEST_METHOD, PATH_INFO and QUERY_STRING, which is why knowledge of CGI transfers directly to modern Python and PHP deployments.

Where CGI is still used and how it is configured

CGI remains a reasonable choice for low-traffic tools, embedded devices and administrative scripts, where simplicity matters more than throughput. Router and printer web interfaces, monitoring tools such as older Nagios front ends, and Git’s git-http-backend all rely on CGI or a close variant.

Server support differs. Apache enables CGI through mod_cgi or mod_cgid with ScriptAlias or the ExecCGI option, and lighttpd provides mod_cgi. Nginx has no native CGI support and requires a wrapper such as fcgiwrap, which runs CGI scripts behind a FastCGI socket. Microsoft IIS supports CGI as an optional role feature.

Use the decision table to judge whether plain CGI fits a workload.

SituationRecommendationReason
Rarely used admin scriptPlain CGI is acceptableStartup cost is irrelevant at low volume
Embedded device with tiny memoryCGI with a compiled binaryNo resident workers consume RAM
Public site with steady trafficFastCGI or an app serverPersistent workers avoid repeated startup
Nginx deployment needing a legacy scriptfcgiwrap wrapperNginx cannot execute CGI directly
Untrusted multi-tenant scriptsCGI with suEXEC or containersPer-request processes isolate users
When plain CGI is a sensible choice

Security risks and common mistakes with CGI

Because CGI passes attacker-controlled input into a real process, mistakes can lead directly to command execution. The Shellshock vulnerability of 2014 showed this vividly: Bash parsed function definitions from environment variables, and since CGI copies HTTP headers into HTTP_* variables, a crafted header could execute arbitrary commands on any server running Bash-based CGI.

  • Shell injection: passing query values to system() or backticks without escaping lets attackers run commands.
  • Writable cgi-bin directories: allowing uploads into an executable directory turns a file upload into code execution.
  • Running as a privileged user: scripts should run under a dedicated low-privilege account, for example through Apache suEXEC.
  • Trusting `CONTENT_LENGTH` blindly: scripts must enforce a maximum body size to prevent memory exhaustion.
  • The httpoxy flaw: a client Proxy header becomes HTTP_PROXY, which some libraries treat as an outbound proxy setting; servers should strip that header.

The safest practice is to validate every input, avoid invoking a shell, keep scripts outside the document root unless they are explicitly mapped, and set timeouts and resource limits so that a hung script cannot block the server.

In simple terms

Think of a web server as a receptionist at a front desk. For a normal page, the receptionist hands over a printed sheet. For a CGI request, the receptionist calls in a specialist, describes what the visitor wants, waits for the specialist to write an answer, and then passes that answer back.

The catch is that a new specialist is called in for every single visitor and sent home afterward. This is simple and safe, because each job is separate, but it becomes slow and expensive when many visitors arrive at once. Newer methods keep the specialists on duty, so the same work happens much faster.

A practical example

A small university lab runs an internal web page where researchers book time on a shared microscope. The page is used about 40 times per day, so the administrator writes a short Python script, places it in Apache’s /cgi-bin/ directory and enables mod_cgid. Each booking request starts the script, which reads the form fields from standard input, writes a row to a SQLite file and prints a confirmation page.

The script takes about 120 milliseconds per request, almost all of it Python startup, which nobody notices at that volume. Two years later the lab opens the calendar to the whole faculty and traffic rises to several requests per second. Response times climb and memory spikes, so the administrator moves the same logic into a small WSGI application served by Gunicorn behind the existing server. The persistent worker cuts response time to about 15 milliseconds, while the original CGI version had been the right, simple choice for its first years.