Apache, Unicorn & SSL

Having used Apache with Mongrel, Thin and Passenger, I’ve now moved on to Unicorn.  Setting up Apache on Ubuntu to proxy to Unicorn requires the following installation commands:

apt-get install apache2 -y
apt-get install libapache2-mod-proxy-html libxml2-dev -y
a2enmod headers
a2enmod proxy
a2enmod proxy_http
a2enmod proxy_balancer
a2enmod rewrite
a2enmod ssl
/etc/init.d/apache2 restart

With these modules in place a virtual host can be configured something like this:

<VirtualHost *:80>
  ServerName     myhost.example.com
  DocumentRoot   /opt/example/app/public

  RewriteEngine On
  # Redirect all non-static requests to unicorn
  RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
  RewriteRule ^/(.*)$ balancer://unicornservers%{REQUEST_URI} [P,QSA,L]

  <Proxy balancer://unicornservers>
    Allow from any
    BalancerMember http://127.0.0.1:8080
  </Proxy>
</VirtualHost>

<VirtualHost *:443>
  ServerName     myhost.example.com
  DocumentRoot   /opt/example/app/public

  RewriteEngine On
  # Redirect all non-static requests to unicorn
  RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
  RewriteRule ^/(.*)$ balancer://unicornservers%{REQUEST_URI} [P,QSA,L]
  RequestHeader set X-Forwarded-Proto "https"

  <Proxy balancer://unicornservers>
    Allow from any
    BalancerMember http://127.0.0.1:8080
  </Proxy>

  SSLEngine     on
  SSLCertificateFile /etc/apache2/ssl/ssl.crt
  SSLCertificateKeyFile /etc/apache2/ssl/ssl.key
</VirtualHost>

mod_headers and the RequestHeader directive are useful if the Rails app is using ssl_requirement.

1 thought on “Apache, Unicorn & SSL

  1. Reply
    Joel - November 9, 2012

    Thank you! I’ve wasted so many hours because I didn’t have that RequestHeader directive in my apache site config. Thank you.

Leave a Reply

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

Scroll to top