Redirect example.com to www.example.com in PlayFra

2019-08-26 04:22发布

问题:

I'm using PlayFramework 1.2.x

I want to redirect the my url example.com to www.example.com

The only thing I could think of was to set this in the application.conf

 prod.application.baseUrl=http://www.example.com/

But this doesn't lead to mydomain.com/some-page being rewritten as www.mydomain.com/some-page

Is this possible within PlayFramework 1.2.x?

P.S. I can make it work for the root url by redirecting to www.example.com, but I need to make this work for all the other pages, and it's not really practical to redirect to a particular URL for the other pages.

EDIT: edited the question to

回答1:

You want to redirect url example.com to www.example.com.

Approach 1:

controller

  @With(CheckUrl.class)
  public  class Application extends Controller{
        public static Result index() {
                return ok(index.render("Unable to resolve host."));
            }
    }

CheckUrl.java

public class CheckUrl extends play.mvc.Action.Simple {

    public F.Promise<SimpleResult> call(Http.Context ctx) throws Throwable {

        String host = request().host();
        System.out.println("HOST IS "+host);

              if (host.equalsIgnoreCase("example.com")) {

             return F.Promise.pure(redirect("http://www.example.com"));

        }

}

So when everytime user hits the url in browser it will be send from controller to CheckUrl.java and redired to wwwdot.It not the cleanest approach so

Approach 2: Standard approach

Source1,Source2