How to Use Varnish with Nginx as SSL Terminator and HTTP to HTTPS Forwarding

nginxUbuntuubuntu-18.04varnish

I have installed varnish and nginx and secured my website with lets encrypt SSL. I tested varnish against nginx cgi cache and i have found out that varnish is a bit faster in my use case (wordpress). So i need some help on how to use nginx for SSL termination with varnish and how to forward http to https as my website is https only. I am running ubuntu 18.04
Please help me someone!!

EDIT: I followed this guide: https://www.linode.com/docs/websites/varnish/use-varnish-and-nginx-to-serve-wordpress-over-ssl-and-http-on-debian-8/

It gives my error in nginx (port 80 already in use)

Please help me!

Best Answer

Assumptions

  • Nginx has a vhost running on port 443 to process incoming HTTPS requests
  • Nginx has a vhost running on port 80 to process incoming HTTP request and redirect them to Varnish
  • Varnish is running on port 6081 and sits behind the HTTPS Nginx vhost
  • Nginx will probably also have a vhost running on port 8080 which does no proxying, but acts as the actual webserver, serving files or PHP requests.

As you can see, my setup differs a little from the one in https://www.linode.com/docs/websites/varnish/use-varnish-and-nginx-to-serve-wordpress-over-ssl-and-http-on-debian-8/. That's because I already tackle HTTP to HTTPS redirection using a separate Nginx vhost.

In this case, Varnish is not listening on port 80, but on 6081.

HTTPS vhost

Here's an example of an Nginx vhost that processes the HTTPS connections:

server {
    listen 443 ssl;
    keepalive_timeout   70;
    server_name example.com www.example.com;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_certificate ssl.crt;
    ssl_certificate_key ssl.key;
    ssl_session_cache   shared:SSL:20m;
    ssl_session_timeout 4h;
    access_log /var/log/nginx/example.com-access.log;
    error_log /var/log/nginx/example.com-error.log;

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://127.0.0.1:6081;
        proxy_http_version 1.1;
    }
}

HTTP to HTTPS redirection vhost

Here's a snippet that redirects HTTP to HTTPS:

server {
        server_name example.com www.example.com;
        listen  80;
        rewrite "^/$" https://example.com permanent;
        rewrite "^/(.+)$" http://example.com/$1 permanent;
}

Redacted content

The vhosts have been redacted and contain example values. Please replace the hostnames accordingly in the server_name expressions.

Please also make sure ssl_certificate and ssl_certificate_key statements point to files that actually exist.

Related Topic