Tips / Nginx

How To Serve Perl Scripts With Nginx

Perl is one of the most popular programming languages of all time. Today, Perl is still used for OS scripting, but not so much for web development (since PHP and other languages exist).

Still, you will sometimes need to launch a Perl script and may find that it’s not working as expected on Nginx. Nginx does not have native support to parse Perl scripts, but there are a few ways to do it with external daemons. It’s almost the same as serving PHP with Nginx.

First, you must set up a PHP daemon, like PHP-FPM. Then, connect to that service via socket/port, using Nginx. In this tutorial, you will learn how to set up a FastCGI wrapper to serve your Perl scripts with Nginx.

How Can You Serve Perl Scripts With Nginx Web Server?

Install the required FastCGI development kit packages:

yum install fcgi  fcgi-devel spawn-fcgi -y

Configure and Install the FastCGI Wrapper

Download, extract, configure, and install the FastCGI wrapper by Grzegorz Nosek:

wget -O fcgiwrap.tar.gz 
tar zxvf fcgiwrap.tar.gz 
cd gnosek-fcgiwrap-* 
autoreconf -i 
make install 
install -d -m 755 /usr/local/sbin
install -m 755 fcgiwrap /usr/local/sbin
install -d -m 755 /usr/local/man/man8
install -m 644 fcgiwrap.8 /usr/local/man/man8

Configure Spawn-FCGI

Spawn-FCGI is the back end Perl-CGI daemon that will process your scripts.

Edit the main configuration file:

nano -w /etc/sysconfig/spawn-fcgi

Add this line at the end:

OPTIONS="-u nginx -g nginx -a -p 9001 -P /var/run/ -- /usr/local/sbin/fcgiwrap"

Edit the Nginx configuration file for your site. Example:

nano -w /etc/nginx/conf.d/

Add this code in the server block section:

location ~ .pl|cgi$ {
        fastcgi_index  index.cgi;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        /etc/nginx/fastcgi_params;

Reload Nginx and start Spawn-FCGI:

service nginx reload
service spawn-fcgi start

Add Spawn-FCGI to the boot process:

chkconfig spawn-fcgi on

Create your Perl script. Example:

nano -w /var/www/

Paste this simple Perl test code:


print "Content-type: text/htmlnn";
print "nn";
print "
n"; print "If you see this, then Perl is running on Nginx"; print "

"; print "n
n"; print "nn";

Assign the proper permissions, so you can parse the file without issues:

chmod 755 /var/www/

The Perl script should look similar to this screenshot:

Perl + Nginx

Your Perl scripts should now be running on Nginx without any issues.

Popular search terms:

  • nginx perl
  • nginx cgi perl
  • nginx perl cgi
  • perl fpm

Esteban Borges

Linux Geek, Webperf Addict, Nginx Fan. CTO @Infranetworking

  • Mike Richardson

    Dude, your code sucks.

    location ~ .pl|cgi$ {
    is wrong!

    • Loc Nguyen

      what is the correct one ?

      • yeah he didnt say..i do see a missing period , and i believe i have my .php location block escaped…..maybe
        location ~ (.pl|.cgi)$ { ….