Redirect Base URL to Contain www Using Nginx For Ghost


We recently started getting the following message from Google Analytics on all of our Ghost sites:

Property All About Ghost is receiving data from redundant hostnames. Some of the redundant hostnames are:

allaboutghost.com
www.allaboutghost.com

Redundant hostnames are counted as separate rows in reports, so hits that are going to the same page on your site from different hostnames will be split into multiple rows. With data split across multiple rows, traffic to specific pages will appear lower than it actually is.

To avoid this problem, consider setting up a 301 redirect from one of your redundant hostnames to the other, or create a search-and-replace filter that strips "www." from hostnames.

To fix this we added a couple of lines to our Nginx configuration file. Our site-available Nginx file looked like this:

server {
    listen 80 default_server;
    listen 443 ssl;

    server_name www.allaboutghost.com allaboutghost.com;
    ssl_certificate        /etc/nginx/ssl/allaboutghost/allaboutghost.com.crt;
    ssl_certificate_key    /etc/nginx/ssl/allaboutghost/allaboutghost.com.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    root /usr/share/nginx/html;
    index index.html index.htm;

    client_max_body_size 10G;

    location / {
        proxy_pass http://localhost:2368;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
    }

And to add the redirect from allaboutghost.com to www.allaboutghost.com we added the following to the top of the file:

server {
    listen 80;
    server_name allaboutghost.com;
    rewrite ^(.*)$ $scheme://www.allaboutghost.com$1;
}

After that all requests for allaboutghost.com will be redirected to have the www. We had tried a different rewrite rule that did do the correct redirect, but it prevented us from getting to the Ghost admin interface because we have the forceAdminSSL: true, so it caused an infinite redirect.

Hope this helps some of you out!