Install Nginx With PHP And MySQL (LEMP Stack) On CentOS 7


In this tutorial I use the hostname with the IP address These settings might differ for you, so you have to replace them where appropriate.


2 Enabling Additional Repositories

Nginx is not available from the official CentOS repositories, so we include the repository of the Nginx project to install it:

vi /etc/yum.repos.d/nginx.repo

     name=nginx repo


3 Installing MySQL

First we install Mariadb. Mariadb is a free fork of MySQL. Run this command on the shell:

yum install mariadb mariadb-server net-tools

Then we create the system startup links for MySQL (so that MySQL starts automatically whenever the system boots) and start the MySQL server:

systemctl enable mariadb.service
systemctl start mariadb.service

Now check that networking is enabled. Run

netstat -tap | grep mysql

It should show something like this:

[[email protected] ~]# netstat -tap | grep mysql
tcp 0 0* LISTEN 10623/mysqld




to set a password for the user root (otherwise anybody can access your MySQL database!):

[[email protected] ~]# mysql_secure_installation
/usr/bin/mysql_secure_installation: line 379: find_mysql_client: command not found


In order to log into MariaDB to secure it, we’ll need the current
password for the root user. If you’ve just installed MariaDB, and
you haven’t set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on…

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] <– ENTER
New password: <– yourrootsqlpassword
Re-enter new password: <– yourrootsqlpassword
Password updated successfully!
Reloading privilege tables..
… Success!

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] <– ENTER
… Success!

Normally, root should only be allowed to connect from ‘localhost’. This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] <– ENTER
… Success!

By default, MariaDB comes with a database named ‘test’ that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] <– ENTER
– Dropping test database…
… Success!
– Removing privileges on test database…
… Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] <– ENTER
… Success!

Cleaning up…

All done! If you’ve completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!
[[email protected] ~]#

[[email protected]~]# mysql_secure_installation

4 Installing Nginx

Nginx is available as a package from which we can install as follows:

yum install nginx

Then we create the system startup links for nginx and start it:

systemctl enable nginx.service
systemctl start nginx.service

There are chances that you get an error like port 80 already in use, error message will be like this

[[email protected] ~]# service nginx start
Starting nginx: nginx: [emerg] bind() to failed (98: Address already in use)
nginx: [emerg] bind() to failed (98: Address already in use)
nginx: [emerg] bind() to failed (98: Address already in use)
nginx: [emerg] bind() to failed (98: Address already in use)
nginx: [emerg] bind() to failed (98: Address already in use)
nginx: [emerg] still could not bind()
[[email protected] ~]#

Then it means that there are chances of apache service running there. Stop the service & further start the service for NGINX as follows

systemctl stop httpd.service
yum remove httpd
systemctl disable httpd.service

systemctl enable nginx.service
systemctl start nginx.service

And open the http and https ports in the firewall

firewall-cmd –permanent –zone=public –add-service=http
firewall-cmd –permanent –zone=public –add-service=https
firewall-cmd –reload

The resulting output on the shell will look like this:

[[email protected] ~]# firewall-cmd –permanent –zone=public –add-service=http
[[email protected] ~]# firewall-cmd –permanent –zone=public –add-service=https
[[email protected] ~]# firewall-cmd –reload
[[email protected] ~]#

Type in your web server’s IP address or hostname into a browser (e.g., and you should see the nginx welcome page:

5 Installing PHP5

We can make PHP5 work in nginx through PHP-FPM (PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites). We can install php-fpm together with php-cli and some PHP5 modules like php-mysql which you need if you want to use MySQL from your PHP scripts as follows:

yum install php-fpm php-cli php-mysql php-gd php-ldap php-odbc php-pdo php-pecl-memcache php-pear php-mbstring php-xml php-xmlrpc php-mbstring php-snmp php-soap

APC is a free and open PHP opcode cacher for caching and optimizing PHP intermediate code. It’s similar to other PHP opcode cachers, such as eAccelerator and Xcache. It is strongly recommended to have one of these installed to speed up your PHP page.

I will install APC from PHP pecl repository. PECL requires the Centos Development tools to beinstalled to compile the APC package.

yum install php-devel
yum groupinstall ‘Development Tools’

and install APC

pecl install apc

[[email protected] ~]# pecl install apc
downloading APC-3.1.13.tgz …
Starting to download APC-3.1.13.tgz (171,591 bytes)
……………..done: 171,591 bytes
55 source files, building
running: phpize
Configuring for:
PHP Api Version: 20100412
Zend Module Api No: 20100525
Zend Extension Api No: 220100525
Enable internal debugging in APC [no] : <– ENTER
Enable per request file info about files used from the APC cache [no] : <– ENTER
Enable spin locks (EXPERIMENTAL) [no] : <– ENTER
Enable memory protection (EXPERIMENTAL) [no] : <– ENTER
Enable pthread mutexes (default) [no] : <– ENTER
Enable pthread read/write locks (EXPERIMENTAL) [yes] : <– ENTER
building in /var/tmp/pear-build-rootVrjsuq/APC-3.1.13

Then open /etc/php.ini and set cgi.fix_pathinfo=0:

vi /etc/php.ini

; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI.  PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is.  For more information on PATH_INFO, see the cgi specs.  Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec.  A setting
; of zero causes PHP to behave as before.  Default is 1.  You should fix your scripts

(Please read to find out why you should do this.)

and add the line:


at the end of the /etc/php.ini file.

In addition to that, in order to avoid timezone errors errors like

[21-July-2014 10:07:08] PHP Warning: phpinfo(): It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘Europe/Berlin’ for ‘CEST/2.0/DST’ instead in /usr/share/nginx/html/info.php on line 2

… in /var/log/php-fpm/www-error.log when you call a PHP script in your browser, you should set date.timezone in /etc/php.ini:

; Defines the default timezone used by the date functions
date.timezone = "Europe/Berlin"

You can find out the correct timezone for your system by running:

cat /etc/sysconfig/clock

[[email protected] nginx]# cat /etc/sysconfig/clock
[[email protected] nginx]#

Next create the system startup links for php-fpm and start it:

systemctl enable php-fpm.service
systemctl start php-fpm.service

PHP-FPM is a daemon process (with the init script /etc/init.d/php-fpm) that runs a FastCGI server on port 9000.


6 Configuring nginx

The nginx configuration is in /etc/nginx/nginx.conf which we open now:

vi /etc/nginx/nginx.conf

The configuration is easy to understand (you can learn more about it here: and here:

First (this is optional) you can increase the number of worker processes and set the keepalive_timeout to a reasonable value:

worker_processes  4;
    keepalive_timeout  2;

The virtual hosts are defined in server {} containers in the /etc/nginx/conf.d directory. Let’s modify the default vhost (in /etc/nginx/conf.d/default.conf) as follows:

vi /etc/nginx/conf.d/default.conf

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

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

    #error_page  404              /404.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;

    # proxy the PHP scripts to Apache listening on
    #location ~ .php$ {
    #    proxy_pass;

    # pass the PHP scripts to FastCGI server listening on

    location ~ .php$ {
        root           /usr/share/nginx/html;
        try_files $uri =404;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
	# deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    location ~ /.ht {
        deny  all;

server_name _; makes this a default catchall vhost (of course, you can as well specify a hostname here like

In the location / part, I’ve added index.php to the index line. root /usr/share/nginx/html; means that the document root is the directory /usr/share/nginx/html.

The important part for PHP is the location ~ .php$ {} stanza. Uncomment it to enable it. Change the root line to the web site’s document root (e.g. root /usr/share/nginx/html;). Please note that I’ve added the line try_files $uri =404; to prevent zero-day exploits (see and,88845,page=3). Please make sure that you change the fastcgi_param line to fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; because otherwise the PHP interpreter won’t find the PHP script that you call in your browser ($document_root translates to /usr/share/nginx/html because that’s what we have set as our document root).

PHP-FPM is listening on port 9000 on by default, therefore we tell nginx to connect to with the line fastcgi_pass;. It is also possible to make PHP-FPM use a Unix socket – I will describe this in chapter 7.

Now save the file and reload nginx:

systemctl restart nginx.service

Now create the following PHP file in the document root /usr/share/nginx/html

vi /usr/share/nginx/html/info.php


Now we call that file in a browser (e.g.

Click to enlarge


As you see, PHP5 is working, and it’s working through FPM/FastCGI, as shown in the Server API line. If you scroll further down, you will see all modules that are already enabled in PHP5, including the MySQL module:

Click to enlarge



7 Making PHP-FPM Use A Unix Socket

By default PHP-FPM is listening on port 9000 on It is also possible to make PHP-FPM use a Unix socket which avoids the TCP overhead. To do this, open /etc/php-fpm.d/www.conf

vi /etc/php-fpm.d/www.conf

… and make the listen line look as follows:

;listen =
listen = /var/run/php-fpm/php5-fpm.sock

Then reload PHP-FPM:

systemctl restart php-fpm.service

Next go through your nginx configuration and all your vhosts and change the line fastcgi_pass; to fastcgi_pass unix:/tmp/php5-fpm.sock;, e.g. like this:

vi /etc/nginx/conf.d/default.conf

    location ~ .php$ {
        root           /usr/share/nginx/html;
        try_files $uri =404;
        fastcgi_pass   unix:/var/run/php-fpm/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;

Finally reload nginx:

systemctl restart nginx.service

You might also like More from author