How to Setup WordPress on Nginx, PHP-FPM and MySQL

WordPress, a widely used blogging platform, can be served using either Apache or NGINX. While Apache is the most popular web server and has served many of the world’s largest websites, an alternative web server, NGINX (pronounced “Engine X”), has been gaining traction. NGINX is an open-source web server and a reverse proxy server for HTTP, SMTP, POP3, and IMAP protocols.

Many web developers and websites have migrated to NGINX due to its scalability, low resource usage, ability to handle many concurrent users, and excellent website performance. For larger and busier websites, it is recommended to host your websites and blogs on a VPS hosting or a dedicated server and run NGINX as a web server.

In this tutorial, we will guide you on how to set up WordPress on NGINX, PHP-FPM, and MySQL. This tutorial assumes that MySQL has been prepared and configured for WordPress and was tested on CentOS 6.5.

Step 1: Prepare the NGINX Repository

The first step is to prepare the NGINX repository. To do this, you need to edit the nginx.repo file located in the /etc/yum.repos.d/ directory. You can use the vi editor to open and edit this file. The content of the nginx.repo file should be as follows:

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

Step 2: Install NGINX, PHP, php-fpm, and MySQL Server

The next step is to install NGINX, PHP, php-fpm, and MySQL server. You can do this by running the following command:

yum install nginx php php-cli php-mysql php-gd php-xml php-fpm mysql mysql-server -y

This command will install NGINX, PHP, php-fpm, and MySQL server on your system.

Step 3: Configure PHP

After installing the necessary software, you need to configure PHP. Open the php.ini file located in the /etc/ directory and set cgi.fix_pathinfo=0. The relevant section of the php.ini file should look like this:

; 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
; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
; http://www.php.net/manual/en/ini.core.php#ini.cgi.fix-pathinfo
cgi.fix_pathinfo=0

Step 4: Set Date Timezone in PHP

Next, you need to set the date.timezone in the php.ini file. The relevant section of the php.ini file should look like this:

[Date]
; Defines the default timezone used by the date functions
; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone
date.timezone = "Asia/Kuala_Lumpur"

Step 5: Configure PHP-FPM to Use a UNIX Socket

This server configuration is set up for PHP-FPM to use a UNIX socket. To do this, open the www.conf file located in the /etc/php-fpm.d/ directory and specify the .sock path and change the user to run php-fpm:

listen = /var/run/php-fpm.sock
user = nginx
group = nginx

Step 6: Backup NGINX Config File

Before making any changes to the NGINX config file, it’s a good practice to create a backup. You can do this by running the following command:

cp -p /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

Step 7: Create sites-available Folder

Next, create a sites-available folder under the /etc/nginx/ directory. This can be done with the following command:

mkdir /etc/nginx/sites-available

Step 8: Adjust NGINX Worker Processes & Connections

NGINX worker processes should equal the number of processors. To check the number of CPUs on your VPS server, use one of the following commands:

lscpu | grep '^CPU(s)'
cat /proc/cpuinfo | grep processor

Then, configure the nginx.conf file as follows:

user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
 worker_connections 1024;
}
http {
 include /etc/nginx/mime.types;
 default_type application/octet-stream;
 log_format main '$remote_addr - $remote_user [$time_local] \"$request\" '
 '$status $body_bytes_sent \"$http_referer\" '
 '\"$http_user_agent\" \"$http_x_forwarded_for\"';
 access_log /var/log/nginx/access.log main;
 sendfile on;
 #tcp_nopush on;
 keepalive_timeout 65;
 gzip on;
 gzip_types text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
 
 include /etc/nginx/sites-available/*.conf;
}

Step 9: Create common.conf and wordpress.conf

Create common.conf and wordpress.conf under the /etc/nginx/conf.d/ folder. The common.conf file should include the following:

# Global configuration file.
# ESSENTIAL : Configure Nginx Listening Port
listen 80;
# ESSENTIAL : Default file to serve. If the first file isn't found,
index index.php index.html index.htm;
# ESSENTIAL : no favicon logs
location = /favicon.ico {
 log_not_found off;
 access_log off;
}
# ESSENTIAL : robots.txt
location = /robots.txt {
 allow all;
 log_not_found off;
 access_log off;
}
# ESSENTIAL : Configure 404 Pages
error_page 404 /404.html;
# ESSENTIAL : Configure 50x Pages
error_page 500 502 503 504 /50x.html;
 location = /50x.html {
 root /usr/share/nginx/html;
 }
# SECURITY : Deny all attempts to access hidden files .abcde
location ~ /\\. {
 deny all;
}
# PERFORMANCE : Set expires headers for static files and turn off logging.
location ~* ^.+\\.(js|css|swf|xml|txt|ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
 access_log off; log_not_found off; expires 30d;
}

The wordpress.conf file should include the following:

# WORDPRESS : Rewrite rules, sends everything through index.php and keeps the appended query string intact
location / {
 try_files $uri $uri/ /index.php?q=$uri&$args;
}
# SECURITY : Deny all attempts to access PHP Files in the uploads directory
location ~* /(?:uploads|files)/.*\\.php$ {
 deny all;
}
# REQUIREMENTS : Enable PHP Support
location ~ \\.php$ {
 # SECURITY : Zero day Exploit Protection
 try_files $uri =404;
 # ENABLE : Enable PHP, listen fpm sock
 fastcgi_split_path_info ^(.+\\.php)(/.+)$;
 fastcgi_pass unix:/var/run/php-fpm.sock;
 fastcgi_index index.php;
 include fastcgi_params;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# PLUGINS : Enable Rewrite Rules for Yoast SEO SiteMap
rewrite ^/sitemap_index\\.xml$ /index.php?sitemap=1 last;
rewrite ^/([^/]+?)-sitemap([0-9]+)?\\.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;

Step 10: Create a Virtual Server

Create a virtual server under the /etc/nginx/sites-available/ directory. For example, if you want to configure a WordPress site with the domain www.webhostinggeeks.local, set up as follows:

server {
 server_name webhostinggeeks.local;
 rewrite ^/(.*)$ http://www.webhostinggeeks.local/$1 permanent;
}
server {
 server_name www.webhostinggeeks.local;
 root /var/www/html/wordpress;
 access_log /var/log/nginx/www.webhostinggeeks.local.access.log;
 error_log /var/log/nginx/www.webhostinggeeks.local.error.log;
 include conf.d/common.conf;
 include conf.d/wordpress.conf;
}

Step 11: Start php-fpm and NGINX

Start php-fpm and NGINX by running the following commands:

/etc/init.d/php-fpm start
Starting php-fpm:                                          [  OK  ]

/etc/init.d/nginx start
Starting nginx:                                            [  OK  ]

Step 12: Enable php-fpm and NGINX at Boot

To ensure that php-fpm and NGINX start at boot, run the following commands:

chkconfig php-fpm on
chkconfig nginx on

Step 13: Verify the Required Port

Finally, verify that the required port is present by running the following command:

netstat -plunt

This command will display the active Internet connections on your server.

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      1042/rpcbind
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      3174/nginx
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1096/sshd
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      3394/mysqld
tcp        0      0 :::111                      :::*                        LISTEN      1042/rpcbind
tcp        0      0 :::22                       :::*                        LISTEN      1096/sshd
udp        0      0 0.0.0.0:111                 0.0.0.0:*                               1042/rpcbind
udp        0      0 0.0.0.0:793                 0.0.0.0:*                               1042/rpcbind
udp        0      0 :::111                      :::*                                    1042/rpcbind
udp        0      0 :::793                      :::*                                    1042/rpcbind

Conclusion

By following these steps, you can successfully set up WordPress on NGINX, PHP-FPM, and MySQL. This configuration provides a scalable and high-performance solution for hosting your WordPress sites.

See also  How to Fix Writable Issue or Error During Joomla CMS Pre-Installation Check on Linux

Remember, for larger and busier websites, it is recommended to host your websites and blogs on a VPS server or a dedicated server and run NGINX as a web server.

For more information on different types of web servers, you can visit our articles on Apache, NGINX, and LiteSpeed.

Commands Mentioned

  • vi /etc/yum.repos.d/nginx.repo – Opens the nginx.repo file for editing
  • yum install nginx php php-cli php-mysql php-gd php-xml php-fpm mysql mysql-server -y – Installs NGINX, PHP, php-fpm, and MySQL server
  • vi /etc/php.ini – Opens the php.ini file for editing
  • vim /etc/php-fpm.d/www.conf – Opens the www.conf file for editing
  • cp -p /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak – Creates a backup of the NGINX config file
  • mkdir /etc/nginx/sites-available – Creates a sites-available folder under the /etc/nginx/ directory
  • lscpu | grep ‘^CPU(s)’ – Checks the number of CPUs on your VPS server
  • cat /proc/cpuinfo | grep processor – Another command to check the number of CPUs on your VPS server
  • vi /etc/nginx/sites-available/webhostinggeeks.local.conf – Opens the webhostinggeeks.local.conf file for editing
  • /etc/init.d/php-fpm start – Starts php-fpm
  • /etc/init.d/nginx start – Starts NGINX
  • chkconfig php-fpm on – Enables php-fpm at boot
  • chkconfig nginx on – Enables NGINX at boot
  • netstat -plunt – Displays the active Internet connections on your server
See also  How to Install and Configure Bind Chroot DNS Server on CentOS 6.4 VPS

FAQ

  1. What is the advantage of using NGINX over Apache?

    NGINX is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption. Unlike Apache, which is a process-driven server, NGINX is event-driven, which allows it to provide high performance under heavy load.

  2. What is PHP-FPM and why is it used?

    PHP-FPM (FastCGI Process Manager) isan alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites. It allows the website to handle strenuous loads, and it provides on-the-fly error handling, a major advantage over the traditional PHP.

  3. What is the purpose of the sites-available directory in NGINX?

    The sites-available directory is typically used to store all of your server block configurations. These configurations are not enabled until they are linked to the sites-enabled directory. This setup allows you to easily enable or disable sites by creating or removing symbolic links.

  4. Why do we need to set cgi.fix_pathinfo=0 in php.ini file?

    Setting cgi.fix_pathinfo=0 in the php.ini file is a security measure. When this setting is enabled (1), the PHP interpreter tries to guess the intended script to execute even when the path is not correctly specified in the request. This behavior could lead to unauthorized code execution. By setting it to 0, we tell PHP not to guess and only execute scripts with a valid path in the request.

  5. What is the role of worker_processes in NGINX?

    The worker_processes directive in NGINX determines how many worker processes are created to handle the load of incoming requests. Each worker process is single-threaded and handles connections in a non-blocking manner. The optimal number of worker processes depends on many factors, but a common approach is to set it equal to the number of CPU cores.

Comments

1 Comment

  • Avatar wapi kilorston says:

    Hi there, I want to express my gratitude for your explanation. I truly admire your exceptional skills and the hard work you’ve put into building this informative website that caters to our interests. I’m new to this, so I’d like to ask for your assistance. Could you guide me on what configuration should be placed in the ‘sites-enabled’ folder? I’m in the process of building my first WordPress website using Nginx and would greatly appreciate your help

Leave a Reply

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