All Linux HowTo's

Nginx & Varnish 4 With HTTPS://

This article explains and gives examples of how to use Varnish 4 to cache in a fully HTTPS environment. This example was created on a CentOS 7 server. Make sure to make SELinux allowances for NginX to listen on port 81.

Here are the facts:

  1. Nginx is listening on ports 80, 443 and 81.
  2. Port 80 is redirected to port 443.
  3. Port 443 reverse-proxies to Varnish 4 listening on port 8080.
  4. Varnish reverse-proxies to Nginx listening on port 81.
  5. Nginx listening on port 81 serves the files from disk.
  6. The FQDN is “www.example.com”.
  7. The host-based firewall needs to permit only 80 and 443 to the public.

This is the Nginx full configuration:

server {
    listen 127.0.0.1:81;
    server_name www.example.com;

    access_log   /var/log/nginx/www.example.com.access-81.log;
    error_log    /var/log/nginx/www.example.com.error-81.log;

    root /var/www/html/www.example.com/wordpress;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ .php$ {
        include fastcgi_params;
        include fastcgi.conf;
        fastcgi_param HTTPS on;
        fastcgi_index  index.php;
        fastcgi_pass   127.0.0.1:9000;
    }
}

server {
    listen 192.168.122.4:443 ssl;
    server_name www.example.com;

    access_log   /var/log/nginx/www.example.com.access-443.log;
    error_log    /var/log/nginx/www.example.com.error-443.log;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
    }

    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

server {
    listen 192.168.122.4:80;
    server_name www.example.com;

    access_log   /var/log/nginx/www.example.com.access-80.log;
    error_log    /var/log/nginx/www.example.com.error-80.log;

    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    }
    return 404;
}

This is the Varnish 4 configuration:

vcl 4.0;
import std;
import directors;

backend default {
  .host = "127.0.0.1";
  .port = "81";
}

sub vcl_deliver {
   if (obj.hits > 0) {
      set resp.http.X-Cache = "HIT";
   } else {
      set resp.http.X-Cache = "MISS";
   }
}

sub vcl_recv {
   set req.http.host = "www.example.com";
   if (req.url ~ "(?i)\.(jpeg|jpg|png|gif|ico|swf|js|css|gz|rar|txt|bzip)$") {
      unset req.http.Cookie;
      return (hash);
   } else {
      return (pass);
   }
}

Similar Posts:

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.