Red Hat / CentOS Install nginx PHP5 FastCGI Webserver

Posted on in Categories , , , , , , last updated June 2, 2009

How do I install and configure a ngnix FastCGI php5 HTTP / web server under Red Hat / RHEL / Fedora / CentOS Linux?

Nginx (engine x) is an HTTP(S) server, reverse proxy and IMAP/POP3 proxy server written by Igor Sysoev. It is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.

Step # 1: Enable EPEL repo

ngnix is not included in the base system. Turn on EPEL repo to install nginx stable release:
# rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/$(uname -m)/epel-release-5-3.noarch.rpm

Step # 2: Install ngnix

Type the following command at a shell prompt:
# yum install nginx
Sample output:

Loaded plugins: downloadonly, fastestmirror, priorities, protectbase
Loading mirror speeds from cached hostfile
 * epel: archive.linux.duke.edu
 * base: ftp.linux.ncsu.edu
 * updates: centos.mirror.nac.net
 * addons: mirror.cs.vt.edu
 * extras: centos.mirror.nac.net
0 packages excluded due to repository protections
Setting up Install Process
Parsing package install arguments
Resolving Dependencies
--> Running transaction check
---> Package nginx.x86_64 0:0.6.34-1.el5 set to be updated
--> Finished Dependency Resolution

Dependencies Resolved

==============================================================================================================================================================
 Package                             Arch                                 Version                                    Repository                          Size
==============================================================================================================================================================
Installing:
 nginx                               x86_64                               0.6.34-1.el5                               epel                               319 k

Transaction Summary
==============================================================================================================================================================
Install      1 Package(s)         
Update       0 Package(s)         
Remove       0 Package(s)         

Total size: 319 k
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing     : nginx                                             [1/1] 

Installed: nginx.x86_64 0:0.6.34-1.el5
Complete!

nginx configuration file

  • Default config file: /etc/nginx/nginx.conf
  • Default SSL config file: /etc/nginx/conf.d/ssl.conf
  • Default virtual hosting config file: /etc/nginx/conf.d/virtual.conf
  • Default documentroot: /usr/share/nginx/html

Configure PHP As FastCGI

Type the following to install php5 with other modules:
# yum install php-pear-Net-Socket php-pear php-common php-gd php-devel php php-mbstring php-pear-Mail php-cli php-imap php-snmp php-pdo php-xml php-pear-Auth-SASL php-ldap php-pear-Net-SMTP php-mysql

Install spawn-fcgi simple program for spawning FastCGI processes

Type the following command:
# yum install spawn-fcgi
Next, download spawn-fcgi init.d shell script:
# wget http://bash.cyberciti.biz/dl/419.sh.zip
# unzip 419.sh.zip
# mv 419.sh /etc/init.d/php_cgi
# chmod +x /etc/init.d/php_cgi

Start php app server, enter:
# /etc/init.d/php_cgi start
# netstat -tulpn | grep :9000

Sample output:

tcp        0      0 127.0.0.1:9000              0.0.0.0:*                   LISTEN      14294/php-cgi

By default php server listens on 127.0.0.1:9000 port. Finally, update /etc/nginx/nginx.conf as follows:
# vi /etc/nginx/nginx.conf
Modify / append as follows:

    location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;
            include        fastcgi_params;
        }

Save and close the file. Restart nginx:
# service nginx restart
Create /usr/share/nginx/html/test.php as follows:

<?php
     phpinfo();
?>

Further readings:

74 comment

  1. Do you have ftp server installed? If so you can add user with adduser command itself:

    useradd  -d /usr/share/nginx/html/ -G nginx -k /dev/null username 
    passwd username
    chown -R username:nginx /usr/share/nginx/html/
    

    Above will get you started. However, for virtual domain you need to do a little more work.

  2. Following is not correct:

    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;

    $document_root should be a full path. Try it as follows and restart server:

    fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;
    1. This case is good:
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

      But.. full path for $document_root is above and can’t by within directive location, otherwise will by issue.

      For example:
      =====
      root /usr/share/nginx/www/www; # my root directory

      location ~ \.php$ { #my directive location for php
      …..
      ….
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      }

      =====

  3. Hi,

    Can you improve the documentation by including cgi-bin for running the scripts (I write my own custom executable scripts using C)?

    I’m using Lighttpd right now…because of poor “straight installation/configuration” Nginx documentation, especially the cgi-bin part.

    Robert

    1. Yes, I will try to cover the following in few days:

      1. Virtual hosting
      2. Cgi-bin via Perl / Python , C etc
      3. Ruby configuration
      4. Proxy configuration etc
      5. Security configuration – chroot jail etc
  4. Hi there,

    May i know how to add PHP_FCGI_MAX_REQUESTS=1000 to spawn fcgi , because i need to add number of request before php-process will be restarted and i don’t know how to add it on spawn fcgi. Thank you.

    Regards,

    Adityo

  5. Hi Vivek,

    Thank you for the quick response, unfortunatelly i cannot find /etc/sysconfig/phpfastcgi on my /etc/sysconfig/ directory should i create a new files ? do you have /etc/sysconfig/phpfastcgi example so i can copy it? thanks.

    Adityo

  6. Hi, Vivek,

    I followed your tutorial and everything work like charm. But when I try to add my virtual hosts, php works fine in the default server but not in the other domains. I read in different forums but I can’t make it work. Do you have any idea of what I’m doing wrong?

    nginx.conf

    server {
    listen 80;
    server_name localhost;

    location / {
    root /usr/share/nginx/html;
    index index.php index.html index.htm;
    }

    error_page 404 /404.html;
    location = /404.html {
    root /usr/share/nginx/html;
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    root /usr/share/nginx/html;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
    root /usr/share/nginx/html;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
    include fastcgi_params;
    }
    }

    virtual.conf

    server {

    listen 80;
    server_name test;

    location / {
    root /usr/share/nginx/test;
    index index.html;
    }
    location ~ \.php$ {
    root /usr/share/nginx/test;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /usr/share/nginx/test$fastcgi_script_name;
    include fastcgi_params;
    }
    }

    When I try to open a php file, the browser try to download it.

    I would appreciate any advise you could give me. Thanks.

    1. This is maybe already solved for you, but the solution is this:

      In the /etc/nginx/conf.d/virtual.conf file use this line:

      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

      Presto!

  7. Hi Vivek!
    I Do exactly the same this How to, but when I try to run test.php in firefox it failed!
    Here’s the result in my browser
    No input file specified.
    I tried to run it in command line mode and I get the result!
    How to solve this error !

  8. Great, works, got it up but when php_cgi crashes, stalls or dies, it doesn’t automatically respawn. I googled extensively and found other people having the same problem. One guy set up a cron job to run every minute to make sure it’s on. Most everyone else seems to have moved to php-fpm, which requires recompiling php, which breaks my virtualmin/webmin. Wish php_cgi would stay alive.

    1. I followed this guide and got the same problem. The solution was on another forum, which worked wonders. Inside the nginx server config, add the line server_name_in_redirect off;

      So:

      server{
      listen 80;
      server_name localhost;
      server_name_in_redirect off;

      }

  9. Thank you for your great article i really appreciate it.

    Thanks to your article i have made my static files server with Nginx :)

  10. Wold it be possible to update this (or a new version) that is focused on installing a low memory LEMP on small bare bones VPS accounts for virtual hosting? Something like:
    Nginx, PHP5, FastCGI, XCache, mySQL, openssh, Bind, wordpress (or lite alternatives)?

  11. Tanks !!!! Work Perfect for my server on Centos 5.4
    ——————————————
    gracias amigo me sirvio de mucho en mi servidor viejito servidor con Centos 5.4

  12. i was installed kloxo with default root directory /home/admin how to sets that with nginx config because after i installed nginx its show forbiden and now i swicth it back to apache

  13. For all who have the problem “The page you are looking for is temporarily unavailable. Please try again later.” after the installation.
    I did a restart of the server started php_cgi and nginx again and everything worked fine.

  14. yep, this guide works.

    the one thing i would add… if you want the php_cgi script starting on boot, u need to add it to the ntsysv list, to do so:

    chkconfig –add php_cgi

    thanks!

  15. Hi Vivek ,

    I am Usha Iyer, an Acquisition Editor with Packt Publishing. As an Acquisition Editor, it is my role to evaluate, develop and ultimately bring book ideas to publication. I am also responsible for finding the right author for any book; bringing them onboard, then working with them as the book is written.

    Recently, I have begun to develop a title on ‘Nginx cookbook’, and am now looking for an author to write this book. The book will consist of some advanced recipes for people already familiar with Nginx.

    You can find some more information about writing for us at Packt’s website http://www.packtpub.com/authors.

    Please contact me if you are interested in writing this book and I would love to discuss the opportunity with you further.

    Thanks,
    Usha
    Email: [email protected]

  16. Hello.

    I installed nginx in centos 5.5 following this guide but i can not start the program:

    service nginx start
    Starting nginx: [FAILED]

    cat /var/log/nginx/error.log
    2010/09/21 19:25:02 [emerg] 3382#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
    2010/09/21 19:25:02 [emerg] 3382#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
    2010/09/21 19:25:02 [emerg] 3382#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
    2010/09/21 19:25:02 [emerg] 3382#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
    2010/09/21 19:25:02 [emerg] 3382#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
    2010/09/21 19:25:02 [emerg] 3382#0: still could not bind()

    Can you help me please?

    1. Dear,
      Just Install putty on you system and open your web host by ip address and then type this command,
      nginx restart, it will start your nginx server and then start your httpd, by httpd restart.
      This command can start your webserver if you are running nginx as a proxy server.

      Thanks.

  17. Hello,

    Is solved, the problem was apache server running in the port 80.

    I installed nginx to run as httpd server for static content.

    thank you.-

  18. thank you VIVEK. great article. i am new in CentOS.
    after doing all thing in this article my server dosn’t work.
    and then i stop the firewall it works. where is the problem.

  19. Great article strait to the point as usual and works.

    For me I have a strange issue I can’t seem to figure and googled and researched a lot to no end. I’ve got php-fastcgi running fine on nginx. However, I’m trying to load memcache and mongo php extensions and for some reason nginx skips right over their ini files in /etc/php.d/. I know memcache and mongo extensions are installed correctly because apache loads them. I’m thinking maybe I need to build php from source and specifically include them in the ./configure .. just a bit gun shy to do this because I’m not sure how this will impact the installation based on this article.

    Thanks

    1. You need to restart or reload both services after installing any php modules and config file in /etc/php.d/memcache.ini. Finally run phpinfo() to see loaded modules.

  20. EXCELLENT tutorial! Thanks!

    Some corrections, if you still maintain this post (I hope you do, since this was a top Google result when I was looking for such instructions)…

    I got 3 issues:

    Retrieving download.fedora.redhat.com/pub/epel/5/x86_64/… error: skipping download.fedora.redhat.com/pub/epel/5/x86_64/… – transfer failed – Unknown or unexpected error warning: u 0x1f876d0 ctrl 0x1f88a40 nrefs != 0 (download.fedora.redhat.com http)

    Cause: The filename is slightly off (probably was updated). It now needs “rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm” (new one ends in “-4” instead of “-3”)

    I got an error when trying to fetch that init.d shell script with wget.
    HTTP request sent, awaiting response… No data received.
    Retrying. (this would loop endlessly)

    Cause: wget failed, I found this command online which worked
    “curl bash.cyberciti.biz/dl/419.sh.zip > 419.sh.zip”

    Last issue was when modifying the nginx.conf file. I got “Unknown directive “location”” error.

    Cause: Due to my own ignorance, I did not realize that this needed to be appended INSIDE the http { … } section of the config, so when you mentioned to append it, i just put it at the end of the file. Fixed by just moving the “location” text to the inside of the http section.

    Overall, GREAT tutorial. Much thanks! …any chance you could do nginx with memcached + virtual host configuration walkthrough too? ;)

    One last note: I am using CentOS 5, so YMMV with these issues I outlined.

  21. $ wget http://bash.cyberciti.biz/dl/419.sh.zip
    --16:17:32--  http://bash.cyberciti.biz/dl/419.sh.zip
    Resolving bash.cyberciti.biz... 75.126.153.206
    Connecting to bash.cyberciti.biz|75.126.153.206|:80... connected.
    HTTP request sent, awaiting response... No data received.
    Retrying.

    Download link works in browser

          1. In case anyone else runs into this, you can workaround this by:

            1) Download it from a browser and copy it over, or:
            2) wget -U=whatever

            It seems to be blocking Wget as a user-agent.

            1. It should only block wget UA when you run the wget continuously. I’ve updated few settings and should work:

               wget http://bash.cyberciti.biz/dl/419.sh.zip
              --2011-06-14 04:52:00--  http://bash.cyberciti.biz/dl/419.sh.zip
              Resolving bash.cyberciti.biz... 75.126.153.206
              Connecting to bash.cyberciti.biz|75.126.153.206|:80... connected.
              HTTP request sent, awaiting response... 200 OK
              Length: 890 [application/zip]
              Saving to: `419.sh.zip'
              
              100%[======================================>] 890         --.-K/s   in 0s      
              
              2011-06-14 04:52:01 (91.4 MB/s) - `419.sh.zip' saved [890/890]
              
  22. Do you know if the Nginx RPM listed at the top of this page has built in IPv6 support or would I need to download the source to enable that?

  23. Thanks a lot for yr article;
    Please, i do exactly your conf,but i still can not have my php pages affiched, in my log error i have thos errors:

    2011/10/03 11:09:51 [error] 7706#0: *16 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: _, request: “GET /index.php HTTP/1.1”, upstream: “fastcgi://127.0.0.1:9000”, host: “127.0.0.1”

    No problem with the Documentroot.
    Have you any idea ?
    Thanks

  24. hello;

    for php-cgi, i had The OK message after starting it, but its show me the error :
    php-cgi is die, but the pid file exist. i try to remove it and touch it again, but its show e the same error message.

    and for server_name is set to localhost;.

  25. hello
    I have same problem and browser download php file.
    Would you please inform us how we can remove this problem ?

    Thanks

  26. Solution for “No input file specified” error while accessing the php files thru browser,

    In nginx.conf file replace the following line,

    line no:69 fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
    to
    fastcgi_param SCRIPT_FILENAME /opt/nginx/html/$fastcgi_script_name;

    where “/opt/nginx/html/” is my webroot path…

  27. We have a server where nginx is installed, we have also configured PHP As FastCGI on the server. Everything is working fine except rewrite rule. Our requirement is to mask an URL

    for eg:- if someone search in our website the URL which comes will be like http://example.com/search.php?searchword=$1 ($1=searched word) . We need to display URL for our customers as http://example.com/$1.html.

    We have set rewrite rule as rewrite ^/(([a-zA-Z_0-9]|-)+/?)$ /search.php?searchword=$1 break;

    The URL is getting redirected however we get a file not found error each time. How can we mask the URL just as we do in Apache. Any help would be greatly appreciated

  28. An error was occurred when I tried to:

    yum install nginx
    Error: Package: nginx-0.8.55-2.el5.i386 (epel)
    Requires: perl(:MODULE_COMPAT_5.8.8)
    You could try using –skip-broken to work around the problem
    You could try running: rpm -Va –nofiles –nodigest

    I tried to:

    Packages skipped because of dependency problems:
    GeoIP-1.4.8-1.el5.i386 from epel
    gd-2.0.35-10.el6.i686 from base
    libxslt-1.1.26-2.el6_3.1.i686 from updates
    nginx-0.8.55-2.el5.i386 from epel

    rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-5.noarch.rpm
    Retrieving http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-5.noarch.rpm
    curl: (22) The requested URL returned error: 404
    error: skipping http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-5.noarch.rpm – transfer failed

    Perhaps you could help me to solve this matter.

  29. Thanks for sharing :)

    I’m having trouble with the php_cgi script.

    Getting this error:
    Starting php-cgi: /etc/init.d/php_cgi: line 38: daemon: command not found

    I can’t find the init.d/functions in my CentOs 6.3 minimum install

    Does anyone know how I get this daemon command?

  30. Is there a way to log errors in php-cgi script or in phpfastcgi ? No errors, no tweaking of the max_requests,max_childrens etc.

Leave a Comment