简体   繁体   中英

Permanent redirect with Play 2.0.x

I'm wondering how to do a permanent redirect 301 in Play framework 2.0.x for subdomains. ex: www.example.com/* redirected to example.com/*. Anyone tried this before ?

The Global object will allow you to intercept the request . For obvious reasons you should do it with GET requests (ie. for SEO purposes), but others, like POST, PUT etc. should be created properly from the beginning in your views.

On the other hand, if it's just some app for serving common HTML pages for life production consider using some HTTP server on front of it - then you can do the trick with some rewriting rule.

import play.GlobalSettings;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.Result;

import java.lang.reflect.Method;

public class Global extends GlobalSettings {

    @Override
    public Action onRequest(final Http.Request request, Method method) {
        if ("GET".equals(request.method()) && "www.example.com".equals(request.host())) {
            return new Action.Simple() {
                public Result call(Http.Context ctx) throws Throwable {
                    return movedPermanently("http://example.com" + request.path());
                }
            };
        }
        return super.onRequest(request, method);
    }
}

In conf/routes file

GET /      controllers.Application.index(path = "")
GET /*path controllers.Application.index(path)

In apps/controllers/Application.scala

object Application extends Controller {
  def index(path: String) = Action {
    Redirect("http://example.com/" + path, status = MOVED_PERMANENTLY)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM