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.
- The web server parses the HTTP request and selects the CGI script from the URL path.
- It builds a set of meta-variables such as
REQUEST_METHOD,QUERY_STRINGandCONTENT_LENGTHand places them in the process environment. - It starts the program and pipes the request body (for example POST form data) to its standard input.
- The program writes response headers, a blank line and then the body to standard output.
- 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.
| Variable | Contents | Typical use |
|---|---|---|
REQUEST_METHOD | GET, POST, HEAD or another method | Choosing how to read input |
QUERY_STRING | Text after the question mark in the URL | Parsing search or filter parameters |
CONTENT_LENGTH | Size of the request body in bytes | Reading exactly that many bytes from standard input |
CONTENT_TYPE | Media type of the body | Detecting form or JSON encoding |
PATH_INFO | Extra path after the script name | Building clean, routed URLs |
REMOTE_ADDR | IP address of the client or proxy | Logging and access decisions |
HTTP_* | Request headers, such as HTTP_USER_AGENT | Reading cookies and client details |
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.
| Stage | Cost | Avoided by persistent workers |
|---|---|---|
| Process creation | Kernel fork and exec on every request | Yes |
| Interpreter startup | Loading the runtime and standard modules | Yes |
| Application loading | Importing frameworks and parsing configuration | Yes |
| Database connection | TCP and authentication handshake | Yes, through pooling |
| Actual request logic | Queries and rendering | No |
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.
| Approach | Process model | Speed | Isolation |
|---|---|---|---|
| CGI | New process per request | Low | Very high |
| FastCGI | Persistent worker pool over a socket | High | High |
| WSGI or ASGI | Persistent Python application server | High | High |
| Embedded module | Interpreter inside the server process | High | Low |
| Reverse proxy to app server | Separate HTTP service behind the server | High | High |
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.
| Situation | Recommendation | Reason |
|---|---|---|
| Rarely used admin script | Plain CGI is acceptable | Startup cost is irrelevant at low volume |
| Embedded device with tiny memory | CGI with a compiled binary | No resident workers consume RAM |
| Public site with steady traffic | FastCGI or an app server | Persistent workers avoid repeated startup |
| Nginx deployment needing a legacy script | fcgiwrap wrapper | Nginx cannot execute CGI directly |
| Untrusted multi-tenant scripts | CGI with suEXEC or containers | Per-request processes isolate users |
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
Proxyheader becomesHTTP_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.