Using NGINX for SSL Termination with Varnish and Magento 2

19 June 2019

Configuring NGINX for SSL termination with varnish can be tricky to get your head around

Even looking at articles found online, it can still be difficult getting the configuration right.Eventually, after some reading and trial and error, we developed a configuration that worked.

Understanding the concept

The below graph shows how nginx handles incoming requests and how they are passed off to varnish, and then back to nginx if required.



The above image shows that any HTTP request is immediately redirected to our HTTPS configuration in NGINX. E.g.



server {
  listen 80;
  server_name domain.co.uk;
  return 301 https://$host$request_uri;
}

In the HTTPS (443/SSL) configuration, we use the below configuration to pass the request to Varnish to serve either cached request or get it from our backend.



servier {
listen 443;
ssl details…
location / {
    proxy_pass http://127.0.0.1:6081;
    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 https;
    proxy_set_header X-Forwarded-Port 443;
    proxy_set_header Host $host;
 }}

The configuration for SSL/443 should be fairly minimal as the configuration for the Magento website (e.g. $MAGE_ROOT) will be declared within the port 8080 NGINX config area.


In our varnish configuration file (default.vlc). We have the following backend configuration:



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

You should also include the Magento 2 Varnish configuration settings (located under STORES > Configuration > ADVANCED > System > Full Page Cache).


And in our Varnish params file (varnish.params) we have used the default port:



VARNISH_LISTEN_PORT=6081

And finally, we have our NGINX configuration for port 8080.

server {
  listen 8080;
  server_name domain.co.uk;
 set $MAGE_ROOT /var/www/vhosts/domain.co.uk/live/httpdocs;
  root $MAGE_ROOT/pub;
 index index.php;
  autoindex off;
  charset UTF-8;
 location / {
    try_files $uri $uri/ /index.php?$args;
  }
etc….
}

As mentioned earlier, in the port 8080 configuration you should use the usual Magento NGINX configuration settings.

INSIGHTS

CONTACT

Are you excited to get your next project up and running? Or are you unsure what is dragging you down?

Contact Us to discuss how we can help increase sales and boost your online performance!
files/ContactUsBlockDesktop_fede44d1-525a-48b1-9790-5fa1703ec11c.jpg

Enter your email address to sign up to our newsletter, featuring case studies, insights, industry news and much more.

If this is something you would like help with, please get in touch.