Nginx and Perl-FastCGI on CentOS 5

Updated by Linode Written by Linode

Contribute on GitHub

Report an Issue | View File | Edit File

This guide has been deprecated and is no longer being maintained.

The nginx web server is a fast, lightweight server designed to efficiently handle the needs of both low and high traffic websites. Although commonly used to serve static content, it’s quite capable of handling dynamic pages as well. This guide will help you get nginx up and running with Perl and FastCGI on your CentOS 5 Linode.

It is assumed that you’ve already followed the steps outlined in our getting started guide. These steps should be performed via a root login to your Linode over SSH.

Set the Hostname

Before you begin installing and configuring the components described in this guide, please make sure you’ve followed our instructions for setting your hostname. Issue the following commands to make sure it is set properly:

hostname -f

The first command should show your short hostname, and the second should show your fully qualified domain name (FQDN).

Install Required Packages

CentOS doesn’t include nginx in their repositories, so you’ll need to add support for EPEL (Extra Packages for Enterprise Linux) from the Fedora project. Issue the following command:

rpm -Uvh

Issue the following commands to update your system and install the nginx web server and compiler tools (Perl should already be installed):

yum update
yum install nginx make automake gcc gcc-c++ fcgi-perl wget
yum install nginx fcg-perl wget
chkconfig --add nginx
chkconfig nginx on
/etc/init.d/nginx start

You’ll be asked to accept the key for EPEL, as it gets imported the first time you install an EPEL package.

Configure Virtual Hosting

In this guide, the domain “” is used as an example site. You should substitute your own domain name in the configuration steps that follow. First, create directories to hold content and log files:

mkdir -p /srv/www/
mkdir /srv/www/
chown -R nginx:nginx /srv/www/

Issue the following commands to create virtual hosting directories:

mkdir /etc/nginx/sites-available
mkdir /etc/nginx/sites-enabled

Add the following lines to your /etc/nginx/nginx.conf file, immediately after the line for include /etc/nginx/conf.d/*.conf:

# Load virtual host configuration files.
include /etc/nginx/sites-enabled/*;

Next, you’ll need to define the site’s virtual host file:

 1 2 3 4 5 6 7 8 910111213141516171819
server {
    listen   80;
    access_log /srv/www/;
    error_log /srv/www/;

    location / {
    root   /srv/www/;
    index  index.html index.htm;

    location ~ \.pl$ {
    gzip off;
    include /etc/nginx/fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  /srv/www/$fastcgi_script_name;

Issue the following commands to enable the site:

cd /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/
/etc/init.d/nginx restart

You may wish to create a test HTML page under /srv/www/ and view it in your browser to verify that nginx is properly serving your site (Perl will not work yet). Please note that this will require an entry in DNS pointing your domain name to your Linode’s IP address (found on the “Remote Access” tab in the Linode Manager).

Configure FastCGI Wrapper

First create the FastCGI wrapper script (credit: Denis S. Filimonov) at /usr/bin/ with the following contents:

 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899

use FCGI;
use Socket;
use POSIX qw(setsid);

require '';


# this keeps the program alive or something after exec'ing perl scripts
END() { } BEGIN() { }
*CORE::GLOBAL::exit = sub { die "fakeexit\nrc=".shift()."\n"; };
eval q{exit};
if ($@) {
    exit unless $@ =~ /^fakeexit/;


sub daemonize() {
    chdir '/'                 or die "Can't chdir to /: $!";
    defined(my $pid = fork)   or die "Can't fork: $!";
    exit if $pid;
    setsid                    or die "Can't start a new session: $!";
    umask 0;

sub main {
        $socket = FCGI::OpenSocket( "", 10 ); #use IP sockets
        $request = FCGI::Request( \*STDIN, \*STDOUT, \*STDERR, \%req_params, $socket );
        if ($request) { request_loop()};
            FCGI::CloseSocket( $socket );

sub request_loop {
        while( $request->Accept() >= 0 ) {

           #processing any STDIN input from WebServer (for CGI-POST actions)
           $stdin_passthrough ='';
           $req_len = 0 + $req_params{'CONTENT_LENGTH'};
           if (($req_params{'REQUEST_METHOD'} eq 'POST') && ($req_len != 0) ){
                my $bytes_read = 0;
                while ($bytes_read < $req_len) {
                        my $data = '';
                        my $bytes = read(STDIN, $data, ($req_len - $bytes_read));
                        last if ($bytes == 0 || !defined($bytes));
                        $stdin_passthrough .= $data;
                        $bytes_read += $bytes;

            #running the cgi app
            if ( (-x $req_params{SCRIPT_FILENAME}) &&  #can I execute this?
                 (-s $req_params{SCRIPT_FILENAME}) &&  #Is this file empty?
                 (-r $req_params{SCRIPT_FILENAME})     #can I read this file?
        pipe(CHILD_RD, PARENT_WR);
        my $pid = open(KID_TO_READ, "-|");
        unless(defined($pid)) {
            print("Content-type: text/plain\r\n\r\n");
                        print "Error: CGI app returned no output - ";
                        print "Executing $req_params{SCRIPT_FILENAME} failed !\n";
        if ($pid > 0) {
            print PARENT_WR $stdin_passthrough;

            while(my $s = <KID_TO_READ>) { print $s; }
            close KID_TO_READ;
            waitpid($pid, 0);
        } else {
                    foreach $key ( keys %req_params){
                       $ENV{$key} = $req_params{$key};
                    # cd to the script's local directory
                    if ($req_params{SCRIPT_FILENAME} =~ /^(.*)\/[^\/]+$/) {
                            chdir $1;

            #fcntl(CHILD_RD, F_DUPFD, 0);
            syscall(&SYS_dup2, fileno(CHILD_RD), 0);
            #open(STDIN, "<&CHILD_RD");
            die("exec failed");
            else {
                print("Content-type: text/plain\r\n\r\n");
                print "Error: No such CGI app - $req_params{SCRIPT_FILENAME} may not ";
                print "exist or is not executable by this process.\n";


Then create an init script to control the FastCGI process that matches the one shown below:

 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
# nginx – this script starts and stops the nginx daemon
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /opt/nginx/conf/nginx.conf
# pidfile: /opt/nginx/logs/

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

prog=$(basename perl)


start() {
    [ -x $perlfastcgi ] || exit 5
    echo -n $"Starting $prog: "
    daemon $perlfastcgi
    [ $retval -eq 0 ] && touch $lockfile
    return $retval

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval

restart() {

reload() {
    echo -n $”Reloading $prog: ”
    killproc $nginx -HUP

force_reload() {
rh_status() {
    status $prog

rh_status_q() {
    rh_status >/dev/null 2>&1

case "$1" in
        rh_status_q && exit 0
        rh_status_q || exit 0
        rh_status_q || exit 7
        rh_status_q || exit 0
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2

Next issue the following commands to make the scripts executable and set the perl-fastcgi process to start on boot:

chmod +x /usr/bin/
chmod +x /etc/rc.d/init.d/perl-fastcgi
/etc/rc.d/init.d/perl-fastcgi start
chkconfig --add perl-fastcgi
chkconfig perl-fastcgi on

Test Perl with FastCGI

Create a file called “” in your site’s “public_html” directory with the following contents:

 1 2 3 4 5 6 7 8 91011121314

print "Content-type:text/html\n\n";
print <<EndOfHTML;
<html><head><title>Perl Environment Variables</title></head>
<h1>Perl Environment Variables</h1>

foreach $key (sort(keys %ENV)) {
    print "$key = $ENV{$key}<br>\n";

print "</body></html>";

Make the script executable by issuing the following command:

chmod a+x /srv/www/

When you visit in your browser, your Perl environment variables should be shown. Congratulations, you’ve configured the nginx web server to use Perl with FastCGI for dynamic content!

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

See Also

comments powered by Disqus

This guide is published under a CC BY-ND 4.0 license.