Search code examples
grailshttp-status-code-301http-redirect

Best practice for redirecting from one web domain to another in Grails?


I am currently working on a filter in Grails that will allow me to redirect all incoming requests on foo.org to the same subpage on foo.com. So far I have been doing the following:

 if(!(""+request.requestURL).toLowerCase().startsWith(
             grailsApplication.config.grails.serverURL ))
    {redirect(url:"${grailsApplication.config.grails.serverURL}${request.requestURI}",params:params) }

Unfortunately, I am experiencing several issues in this approach:

  1. The request.requestURI value seems to behave differently than expected: instead of giving me the normal "/[controller]/[action]" pattern as I would expect, it returns something like: "/grails/[controller]/[action].dispatch". - Is there an alternative way to obtain the "normal" URI? (excuse me if this is trivial, but have not been able to find it in the documentation, nor by trying out the various methods available on the request object)
  2. Params are not being passed in the above redirect. This is probably due to the fact that I am using the "url" parameter in the redirect which according to the docs is supposed to be used for redirects to absolute paths (which again causes it to ignore the params section?). However, since I will not be able to use the normal redirect(controller:...,action:...) approach when redirecting to another domain what approach could I use in order to pass the params correctly along to the subpage on foo.com ? Am considering a solution where I will add the params manually via a params.each{} closure, but isn't there a more elegant solution to this?
  3. 301 redirects. Since my redirects are of a permanent nature, I would like to use the 301 status code. I have tried to set "response.status = 301" but it seems to be ignored when using the Grails redirect(...) method. Further I can see from grails.org that this seems to be introduced with grails 2.0, but is there a way to obtain this already now in Grails 1.3.7?

Solution

    1. Use request.forwardURI.

    2. If you have meant GET params, then it should be resolved using the above URI?

    3. I think 301 redirects are not possible using classic redirect. You can do this in a filter like this, which is obviously not the cleanest way:

      def filters = {
          all(controller:'*', action:'*') {
              before = {
                  if (request.serverName == "foo.org") {
                      response.setStatus(301);
                      response.setHeader("Location", "http://foo.com" + request.forwardURI)
                      response.flushBuffer()
                      return false; // return false, otherwise request is handled from controller
                  }
              }
          }
      }