HTTPS with Varnish and Apache

From wiki.techunit.org
Jump to: navigation, search

Introduction

The target

To implement a Varnish cache in a HTTPS Web Cluster, to improve performance. Varnish Cache is a caching HTTP reverse proxy, it does not support HTTPS protocol. So to add Varnish on your HTTPS web service, you will need to use URL rewriting and Proxy mode.

Useful links

Optimize your web performance with Varnish Cache

Apache web server documentation

Configuration

Required

Configure HTTP virtualhost

  • Edit /etc/apache2/sites-available/www.example.com.conf
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /opt/www.example.com
DirectoryIndex index.php index.html
</VirtualHost>
  • Enable vhost
a2ensite www.example.com

Configure varnish

  • No need to modify configuration
  • Check the listening port in /etc/default/varnish (default 6081)
  • Configure your backend in /etc/varnish/default.vcl
    • Single server, keep default (127.0.0.1:80)
    • Frontend/Backend architecture
backend www.example.com {
    .host = "10.0.0.3"; # or hostname
    .port = "80";
}
  • Restart varnish

Configure HTTPS Vhost

  • Edit /etc/apache2/sites-available/www.example.com-ssl.conf
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName www.example.com
SSLEngine On
SSLCertificateFile /path/to/your/www.example.com.crt.pem
SSLCertificateKeyFile /path/to/your/www.example.com.key.pem

ProxyPreserveHost On
ProxyRequests off
ProxyPass / http://www.example.com:6081/
ProxyPassReverse / http://www.example.com:6081/
</VirtualHost>
</IfModule>
  • Enable it and reload apache2

Rewrite HTTP to HTTPS (Optional)

  • Enable rewrite apache mod
  • Edit /etc/apache2/sites-available/www.example.com.conf
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /opt/www.example.com
DirectoryIndex index.php index.html

RewriteEngine on
RewriteCond %{HTTPS} !on
# Add the following line only if you have single server (varnish and apache on the same server)
RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$

RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
</VirtualHost>

Elliot
techUnit's cofounder