The Common Gateway Interface, usually called CGI, is a protocol for connecting an HTTP server to a separate program that generates a response. It was fundamental to the early dynamic web: rather than serving only a file from disk, a server could invoke a program, provide information about a request and return the program’s output to the client. CGI still matters as an architectural idea because it makes the boundary between HTTP transport and application execution explicit. But a historical CGI script is not the default recommendation for building a new production web service in 2026.
CGI/1.1 is described in RFC 3875, an informational specification published in 2004 that documents a practice used on the web since the early 1990s. The document describes request meta-variables, how request bodies are supplied, and how a program constructs a response. It is not a security guarantee or a recommendation to deploy unmaintained CGI applications. The specification itself warns about malformed input, request handling and the risks of executing external programs. Understanding those constraints is more useful than romanticizing CGI as a universal solution to web development.
Follow the boundary between the web server and an application
In a simple static site, the server identifies a resource and sends its contents. In CGI, the server selects a program to handle a request, prepares an execution environment, supplies request data and interprets the program’s output. The application code is responsible for its business logic, such as calculating a result, looking up a record or building an HTML document. The server remains responsible for network transport and turning the program output into the HTTP response returned to the client.
This separation introduces a critical trust boundary. A client controls parts of the URL, headers and request body. The server may convert those into environment variables and data passed to the program, but that conversion does not make them trustworthy. A script that assembles shell commands, SQL queries or filesystem paths from request values without validation can expose the server. Even a small classroom example should distinguish parsing data from executing it or using it to choose a sensitive resource.
The classic CGI model commonly starts an external process for each request. That is simple to understand and isolates the process lifetime, but process startup can become expensive under heavy traffic. Web servers and frameworks later adopted many other integration and execution patterns, including persistent application workers and managed runtimes. The key comparison is not that CGI is inherently unusable; it is that resource cost, process isolation, lifecycle control and operational maintenance must be weighed against alternatives.
Understand the request information available to a CGI program
A CGI program receives request metadata through named variables. These may describe the request method, the path selected by the server, the query string, content type and content length. Examples include REQUEST_METHOD, QUERY_STRING, CONTENT_TYPE, CONTENT_LENGTH and GATEWAY_INTERFACE. They are part of the interface agreement, not arbitrary names invented by one application. RFC 3875 defines expectations for many of them and how an HTTP server supplies them.
In a GET request, application parameters often appear in the query string, although a program must still parse and validate the relevant encoding. URL encoding does not imply correctness, authorization or safe use in a database query. A POST request may carry data in a message body, which conventional CGI exposes through standard input. When a content length is provided, a script must respect it rather than reading arbitrary additional input and assuming every stream has the same termination behavior.
Headers and metadata should not be treated as reliable proof of client identity. An upstream proxy can alter the apparent network address, and forwarding headers can be spoofed unless the deployment has a trusted proxy policy. Authentication and authorization must be designed deliberately. A form containing a user identifier does not prove that the caller is entitled to read that user’s records, and a script should not bypass the server’s security boundary because the request arrived through an HTTP connection.
Construct a valid response rather than printing arbitrary text
A CGI program returns a header section followed by an empty line and optionally a response body. For an HTML document, its output ordinarily includes a header such as Content-Type: text/html; charset=UTF-8, then the blank line, then the generated HTML. The server converts this into an HTTP response. If the script fails before producing valid headers, a browser may receive an error rather than usable page content. Response construction therefore is part of the application contract.
The program can communicate a response status through the CGI Status header. Redirect behavior has its own rules; merely printing a URL in the body does not create an HTTP redirect. Applications also need to escape untrusted data in the output context where it appears. User input inserted directly into HTML can produce cross-site scripting even when the CGI request parsing itself was correct. A safe demonstration treats encoding and output construction as separate tasks.
For a small historical exercise, trace a request that collects a name and returns a greeting. Record the query parameters or body bytes, what validation happens, the generated headers and the final HTML escaping. Then change the input to include characters used in HTML and verify the response still displays literal text. That exercise teaches the interface and the security boundary without asking learners to expose an obsolete script to the open internet.
See how CGI scripts interacted with databases and files
Early applications used CGI programs for guestbooks, search forms, simple administration panels and catalog lookups. An application might accept a search term, query a database and emit matching records as an HTML page. This made web pages interactive, but it also created risks associated with input handling, database credentials, error messages and concurrent use. Those risks did not disappear with modern frameworks; they became better understood and managed through application architecture and tested libraries.
Database access should use parameterized statements and the minimum privileges required for the operation. Access to files should be restricted to intentional directories and filenames. A program must not transform an arbitrary URL path into an unrestricted filesystem read. Similarly, an uploaded filename or submitted form value must not become a shell command. The primary lesson is that receiving a parameter and trusting it are two different events, irrespective of which programming language implements the interface.
Concurrency and recovery are important even for historical systems. Two requests may attempt to modify the same state, and an interrupted process may leave a partially completed operation. A CGI program should use appropriate transaction boundaries and error handling, and a server should have a plan for timeouts and resource limits. Testing only a single successful form submission misses much of what determines whether the application will behave reliably.
Compare the historical model with modern web application patterns
Modern web services commonly run application workers or processes that remain available across requests. They may use an HTTP server, reverse proxy, load balancer and application framework, each with responsibilities for routing, transport security, authentication and application logic. That arrangement can make connection pooling, caching, structured logging and deployment management easier. It does not automatically make the application secure; threat modeling, validation and least-privilege access remain essential.
Frameworks also abstract request parsing, response formatting and common security controls. An application built with a modern Java framework, for example, often exposes an HTTP service without a separate CGI executable per request. The Spring Boot REST API development model is a useful contrast because routing and request handling operate inside a managed application process rather than conventional CGI script invocation.
Persistent workers introduce their own concerns: shared process state, memory leaks, connection lifecycle, resource competition, deployment health checks and graceful shutdown. The lesson is not that CGI was replaced by a single universally superior pattern. Different integration models trade simplicity, isolation, operational efficiency and platform compatibility. Understanding these trade-offs helps developers select the appropriate approach instead of repeating a technology-fashion rule.
Audit a CGI legacy application before attempting migration
Some organizations still encounter CGI in supported legacy systems, embedded administration tools or older institutional applications. Before replacing one, identify the exact server, interpreter, dependencies and process execution permissions. Determine which paths invoke scripts, what environment variables they assume, which files and databases they read, and how authentication is enforced. A replacement that preserves the visible HTML but changes the treatment of credentials or form fields may break users or create a security defect.
Map inputs and outputs explicitly. Include query parameters, body encoding, cookies, response headers, redirects, generated content and error paths. Then document external dependencies and how the application handles concurrent changes. If the environment uses nonstandard CGI extensions, distinguish them from RFC-defined behavior. A controlled test environment can reveal implicit assumptions that were never written into the old source code.
A migration should be verified with representative safe inputs, malformed input, authorization failures and output escaping. Compare response behavior and business outcomes rather than checking only whether a page loads. If the old script writes data, test idempotency, transactions and failure recovery. When evidence is incomplete, an incremental migration behind a stable interface can be less risky than a wholesale rewrite performed solely to replace a dated technology.
Use CGI knowledge for architectural reasoning
CGI provides a particularly clear example of a software interface: a web server prepares request metadata and input bytes; an application performs a bounded task; the server interprets its returned headers and content. This helps learners recognize the boundaries among networking, process execution, application logic and trust. These boundaries remain relevant to APIs, serverless functions and web frameworks even though their runtime models differ from classic CGI.
A technically useful explanation should be able to answer four questions: what supplies the request data, what validates it, what performs the business action, and what controls the response and execution environment? If those responsibilities are not clear, performance and security advice will be speculative. The CGI model makes the questions visible and provides a stepping stone toward modern system design.
CGI’s historical contribution was enabling dynamic websites with a straightforward server-to-program contract. Its modern value is in understanding that contract, its constraints and safe migration of legacy code—not in urging every developer to create a new CGI deployment. For exact behavior, consult RFC 3875: The Common Gateway Interface Version 1.1 and the documentation for the particular server and supported runtime in use.