How To Speed Up Nginx on CentOS

Updated on September 11, 2015
How To Speed Up Nginx on CentOS header image


This tutorial will teach you how to optimize a website that is being hosted with Nginx. We'll be doing the following:

  • Removing Nginx.
  • Recompiling Nginx with SPDY3, OpenSSL, and Gzip.
  • Installing any 3rd party modules needed.

Steps in this tutorial have been tested on both CentOS 6 and 7. In addition, both 32-bit and 64-bit architectures were tested working.


Let's get started with the removal of Nginx. Also, we'll need to have OpenSSL and a few dependencies installed before we compile Nginx again.

Step 1: Backup old configuration and data

cd ~
mkdir nginx
cp -r /etc/nginx ~/nginx

Step 2: Remove Nginx

yum remove nginx

Step 3: Install OpenSSL and its dependencies

yum install zlib-devel pcre-devel openssl libssl-devel make gcc gcc-c++ -y

Compile Nginx

Now that we're done with the removal of Nginx, we can compile it from source.

Step 1: Use wget to retrieve the Nginx source code

cd ~

Step 2: Extract the tarball

tar -xvf nginx-1.8.0.tar.gz

Step 3: Build and install Nginx

cd ~/nginx-1.8.0
./configure --with-http_spdy_module --with-http_ssl_module --with-http_gzip_static_module
make install

Step 4: Setup Nginx as a service

We will use a third-party script from GitHub for the init.d service.

cd /etc/init.d
chmod +x nginx

Step 5: Configure Nginx

At this point, you can move your old configuration back to the /etc/nginx folder.

Start Nginx.

service nginx start

Begin editing the Nginx configuration.

vi /etc/nginx/nginx.conf

Within the "http" block, add the following:

gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;	
gzip_http_version 1.1;	
gzip_types text/plain text/css text/JavaScript;

Exit and save the file by hitting the escape key, proceeded with typing :wq, then hitting enter.

Reload Nginx. This is known as a soft restart.

service nginx reload


Congratulations! You have now compiled and optimized Nginx. Going forward, you should see a performance gain in page loads on your website.

Note that adding more modules to Nginx is not possible after it has been compiled. See the bonus section below for information about adding modules.

Optional: Install additional modules

To add modules to Nginx, you will have to repeat the compile process from this tutorial. Start by removing Nginx again. When you get to the step starting with ./configure ..., you can add modules with this syntax:

--add-module=/<module location>

This argument can be repeated if you have more than one module.