How to Run CGI Script with Nginx

To run CGI scripts with Nginx, you can use the fcgiwrap package.

1. Install Nginx and fcgiwrap

apt update
apt install nginx fcgiwrap

2. Enable and start fcgiwrap

systemctl enable fcgiwrap
systemctl start fcgiwrap
systemctl status fcgiwrap

3. Configure Nginx

Edit the server entry of the website for which you need CGI enabled and add the following configuration. Replace /var/www/html with the actual document root of your website.

location ~ \.cgi$ {
    gzip off;
    root /var/www/html;
    fastcgi_pass unix:/var/run/fcgiwrap.socket;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    # Optional: If you want to allow PATH_INFO (e.g., /script.cgi/path/info)
    # fastcgi_split_path_info ^(.+\.cgi)(/.*)$;
    # fastcgi_param PATH_INFO $fastcgi_path_info;
}

Example Configuration:

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

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }
    
    location ~ \.cgi$ {
        gzip off;
        root /var/www/html;
        fastcgi_pass unix:/var/run/fcgiwrap.socket;
        include /etc/nginx/fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        # Optional: If you want to allow PATH_INFO (e.g., /script.cgi/path/info)
        # fastcgi_split_path_info ^(.+\.cgi)(/.*)$;
        # fastcgi_param PATH_INFO $fastcgi_path_info;
    }    
}

4. Restart Nginx

systemctl restart nginx

5. Create a CGI File

Python Example:

nano /var/www/html/test.cgi

Add the following content:

#!/usr/bin/python3
print("Content-type: text/html\n")
print("<html><body>")
print("<h1>CGI is Working!</h1>")
print("<p>This is a test script run by fcgiwrap and Nginx.</p>")
import os
print("<p>Environment variables:</p>")
for key, value in os.environ.items():
    print(f"<p>{key}: {value}</p>")
print("</body></html>")

The first line of the script specifies it’s a Python script. If you don’t have Python 3 installed, you need to install it. Verify it works with:

/usr/bin/python3 -V

Make the CGI script executable:

chmod 755 /var/www/html/test.cgi

PHP Example:

First, install the php-cgi package:

apt install php-cgi

Create the file:

nano /var/www/html/test.cgi

Add the following content:

#!/usr/bin/php-cgi
<?php
header("Content-type: text/plain");
echo "Hello World\n";
echo "Welcome";
?>

Make the CGI script executable:

chmod 755 /var/www/html/test.cgi

Now you can access your scripts at:

http://your-server-ip/test.cgi

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *