heroku godaddy域名java堆栈SSL设置

时间:2012-02-16 20:26:35

标签: java ssl heroku cedar

我正在尝试为我的heroku java应用程序设置SSL。我跟着http://devcenter.heroku.com/articles/ssl在secure.mydomain.com上设置了SSL。如果我做https://secure.mydomain.com,一切都会很好。但是,

1)如何将所有http流量转发到https?有人可以共享示例代码吗?即如果我去http://secure.mydomain.com,它应该转发我https://secure.mydomain.com

2)我只有secure.mydomain.com的证书。我可以在godaddy中为www.mydomain.com设置CNAME,以将我的所有流量转发到https://secure.mydomain.com

简而言之,我想向mydomain.com,www.mydomain.com和secure.mydomain.com提出所有要求转发给https://secure.mydomain.com的请求。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我确信这段代码可能会有点偏差,它可能会遗漏一些极端情况,但这里是一个通用的servlet过滤器,它会将所有http流量重定向到https

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecureFilter implements Filter {

    public void init(FilterConfig arg0) throws ServletException {}
    public void destroy() {}

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
            throws IOException, ServletException {

        HttpServletRequest hr = (HttpServletRequest) req;
        HttpServletResponse hs = (HttpServletResponse) res;

        if(req.isSecure() || 
            (hr.getHeader("X-Forwarded-Proto")!=null && 
             hr.getHeader("X-Forwarded-Proto").equals("https"))) {
            chain.doFilter(req,res);
        } else {
            hs.sendRedirect("https://"+
                            hr.getHeader("Host")+
                            hr.getRequestURI()+
                            (hr.getQueryString()!=null? "?"+hr.getQueryString():""));
        }
    }
}

将以下内容插入web.xml

,将其添加到您的应用中
<filter>
    <filter-name>SecureFilter</filter-name>
    <filter-class>SecureFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SecureFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>