Configure Nginx + Varnish + Apache for CentOS

In this tutorial, we are going to configure Nginx + Varnish + Apache. We will use Nginx for front end, Apache for back-end and Varnish for cache. In the end of the configuration, your web server will be run on this port:

Nginx: Port 80
Varnish: Port 8080
HTTPD(Apache): Port 8081

Preparation

Nginx Installation
yum install epel-release
yum install nginx
systemctl start nginx
systemctl enable nginx
Varnish Cache Installation
yum install varnish
systemctl start varnish
systemctl enable varnish
Apache Installation
yum install httpd
systemctl start httpd
systemctl enable httpd

Configuration

Nginx Configuration
sudo nano /etc/nginx/nginx.conf

Your Nginx.conf will look like this

server {
	listen 80;
    server_name newtesting.com;
    location ~ ^/(images|javascript|js|css|flash|media|static)/ {
    	root /var/www/html;
    	index index.php index.html;
        expires 30d;
	}
location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto http;
    proxy_set_header X-Forwarded-Port 80;
    proxy_set_header Host $host;
  }
}
Varnish Configuration
sudo nano /etc/varnish/default.vcl

Your default.vcl will look like this

# Default backend definition. Set this to point to your content server.
backend default {
  .host = "YOUR_SERVER_IP_ADDRESS";
  .port = "8081";
  .connect_timeout = 200s;
  .first_byte_timeout = 200s; 
  .between_bytes_timeout = 200s; 
}
Apache Configuration
sudo nano /etc/apache2/httpd.conf

If the httpd.conf is doesn’t exist. Try another one in the list below that most Apache configuration file is located.

  • /etc/apache2/httpd.conf
  • /etc/apache2/apache2.conf
  • /etc/httpd/httpd.conf
  • /etc/httpd/conf/httpd.conf
<VirtualHost *:8081>
  ServerName YOURSERVERNAME.com
  DocumentRoot /var/www/html
  <Directory /var/www/html>
    Options Indexes FollowSymLinks
  </Directory>
</VirtualHost>

Verify Server Configuration

Once you have set all these configurations file correctly. You can verify the listening ports by running the command below.

netstat -plant | grep LISTEN

The port should be matched as the list below. If it doesn’t match, please check the configuration file again.

  • Nginx: Port 80
  • Varnish: Port 8080
  • HTTPD(Apache): Port 8081

You can also run Curl to check your server configuration.

curl -I localhost

If everything configured correctly, you should see you’re running nginx as a server and X-Varnish will be appear there. If you don’t see it, you probably missed some steps. Going back and configure again.

HTTP/1.1 200 OK
Server: nginx/1.17.8
Date: Tue, 17 Feb 2020 01:07:13 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 9
Connection: keep-alive
Last-Modified: Thu, 16 Feb 2020 23:47:57 GMT
ETag: "1301328451"
X-Varnish: 1626359724
Age: 0
Via: 1.1 varnish-v4