perwendel / spark

A simple expressive web framework for java. Spark has a kotlin DSL https://github.com/perwendel/spark-kotlin
Apache License 2.0
9.64k stars 1.56k forks source link

Redirect http to https for static files #974

Open amc6 opened 6 years ago

amc6 commented 6 years ago

I'm trying to get https redirecting working for all requests to my server. The following snippet of code works for redirecting all requests except those that are for static files since those appear to be processed and returned before the before filters are run. Is there some other way of accomplishing this?

Spark.before(Filter { request, response ->
    if (request.scheme() != "https") {
        val url = request.url()
        val newUrl = StringBuilder(url).insert(4, 's').toString()
        response.redirect(newUrl, Redirect.Status.PERMANENT_REDIRECT.intValue())
        Spark.halt(Redirect.Status.PERMANENT_REDIRECT.intValue())
    }
})
dbrezack commented 6 years ago

I just spun up 2 servers one on 80 another on 443, the 80 server redirects all traffic to the 443 server. It works for static files and dynamic routes

amc6 commented 6 years ago

You're using the code I have above? Or is it working automatically or doing something else?

Assuming you are using my above code, then I must be missing something. Because I don't know how the redirect could be working for static files. See https://github.com/perwendel/spark/blob/master/src/main/java/spark/http/matching/MatcherFilter.java#L96 It checks for static files and returns before ever attempting to run filters.

dbrezack commented 6 years ago

This is how mine is setup the if(port == 8080) is just for local/deployment options

        String external = configUtils.getExternalFile();
        int port = 443;
        Service https = Service.ignite()
                .port(port)
                .threadPool(32)
                .externalStaticFileLocation(external);
        https.staticFiles.expireTime(60*60*16);
        if(port != 8080) {
            https.secure("cert.jks", "Password", null, null);
            Service http = Service.ignite().port(80);
            http.before(((request, response) -> {
                final String url = request.url();
                if (url.startsWith("http://"))
                {
                    final String[] split = url.split("http://");
                    response.redirect("https://" + split[1]);
                }
            }));
        }