Kyle Banks

Redirecting WWW to Root with Grails

Written by @kylewbanks on Mar 14, 2013.

Having the same content available at www.yourdomain.com and yourdomain.com is bad for SEO, because it counts as duplicate content. Not allowing users to go to www or root is even worse, as most users will simply assume the website is broken, or nonexistent. The solution is to redirect from one to the other, allowing users to go to whichever they prefer, and removing the issue of duplicate content. I prefer to redirect from www to the root domain because I find the URL to be cleaner this way, but it's entirely up to you.

In order to achieve this in Grails, we simply need to add a file to grails-app/conf called DomainFilters.groovy (any groovy file ending with 'Filters' in the conf directory will produce the same results).

class DomainFilters {
    def filters = {
        wwwCheck(uri:'/**') {
            before = {
                if (request.getServerName().toLowerCase().startsWith("www.")) {
                    int port = request.getServerPort();

                    if (request.getScheme().equalsIgnoreCase("http") && port == 80) {
                        port = -1;
                    }

                    URL redirectURL = new URL(request.getScheme(), request.getServerName().replaceFirst("www.",""), port, request.forwardURI);

                    response.setStatus(301)
                    response.setHeader("Location", redirectURL.toString())
                    response.flushBuffer()
                }
            }
        }
    }
}

The wwwCheck filter checks all requests for the www. prefix, and if found, redirects to the same URL, without the www. subdomain. It is important to return the 301 response because it informs the browser (and search engine crawlers) that this is a permanent redirect. There will never be content specific to www..

If your server listens for https requests (or any requests on ports other than 80), you can add checks using the same format, replacing http and port 80 with the appropriate values. You can also redirect from any subdomain you want to the root site (or another subdomain), by simply swapping www with your subdomain.

If you want to see this in action, try to visit http://www.kylewbanks.com. Notice that you are seamlessly redirected to http://kylewbanks.com.

Let me know if this post was helpful on Twitter @kylewbanks or down below!