Force multiple websites with NGinx, Varnish and dedicated IP’s from non-www to www

I’m dealing with this for days and need help fellows! I hope somebody here han solve this:

3 WordPress websites (3 dedicated IP’s)

Read More

I’ve used this Ansible playbook to deploy: https://github.com/zach-adams/hgv-deploy-full

This is the fullstack:

Ubuntu 14.04 (Dedicated Server, no firewall)

  • Percona DB (MySQL)
  • HHVM (Default PHP Parser)
  • PHP-FPM (Backup PHP Parser)
  • Nginx Varnish (Running by default)
  • Memcached and APC
  • Clean WordPress Install (Latest Version)
  • WP-CLI

All working ok. I checked headers and Varnish is working. When I try to force 301 from non-www to www with Varnish in each individual site, it enter in a url redirect loop. I added to the Nginx configuration this line as i read in some documentation:

server {
    server_name example.com;
    return 301 $scheme://www.example.com$request_uri;
}

It doesn’t work and i think it’s for the Varnish configuration. I followed some of this documentation but nothing worked for me:

I hope somebody can illuminate me 🙂

Related posts

Leave a Reply

1 comment

  1. In order to redirect from non-www to www using Varnish you will neeed to do the following:

    1- Disable any redirect rules that written in nginx configuration.

    2- redirect non-www to www through varnish using the following snippet:

    sub vcl_recv {
        if (req.http.host == "example.com") {
            set req.http.host = "www.example.com";
            error 750 "http://" + req.http.host + req.url;
        }
    }
    
    sub vcl_error {
        if (obj.status == 750) {
            set obj.http.Location = obj.response;
            set obj.status = 301;
            return(deliver);
        }
    }
    

    Note: I used the above snippet today and it worked correctly for me (it will work with Varnish 3 which is used in the playbook that mentioned in your question)

    If you would like to redirect using nginx you can try this:

    server {
        listen 8080; # modify this with your current nginx port
        server_name  example.com;
        return 301 $scheme://www.example.com$request_uri;
    }
    server {
        listen 8080; # modify this with your current nginx port
        server_name www.example.com;
        root /path/to/example/files/;
        # ...the rest of your config file goes here...
    }
    

    Use one method only either varnish or nginx. In case you have nginx as the front end i suggest you to go with nginx way.