Web App With C & FastCGI - Quick Start

Minimal app and Nginx configuration.

Updated December 7, 2022

Table of contents

Quick Start

Install libfcgi-dev and nginx:

sudo apt-get update
sudo apt-get install libfcgi-dev nginx

Create main.c and add these lines to it:

#include <fcgiapp.h>
#include <stdio.h>

int main() {

	FCGX_Init();
	int Socket = FCGX_OpenSocket("127.0.0.1:2016", 1024);
	FCGX_Request Request;
	FCGX_InitRequest(&Request, Socket, 0);

	while(FCGX_Accept_r(&Request) >= 0) {
		printf("Request Accepted\n");
		FCGX_FPrintF(
			Request.out,
			"Content-type: text/html\r\n\r\n"
			"<h1>Hello.</h1>"
			);
		FCGX_Finish_r(&Request);
	}
	
	return 0;
}

Replace /etc/nginx/sites-enabled/default contents with these lines:

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _;

    location / {
        fastcgi_pass 127.0.0.1:2016;
        include fastcgi_params;
    }
}

Run these commands:

sudo service nginx restart
cc main.c -o app.fcgi -lfcgi
./app.fcgi

Open a new terminal and make a request to port 80:

curl localhost

You should see the response body:

<h1>Hello.</h1>

Leave a comment

You can use Markdown to format your comment.