1.首先去騰訊雲或者阿里雲申請免費ssl證書,以騰訊云爲例,不建議自己生成,因爲沒辦法測試發佈環境的效果,填寫個人信息,最後提示審覈中才是申請成功,審覈比較快,半小時就通過了。
2.下載已經通過審覈的證書文件夾,解壓文件如下,根據項目選擇使用,
3.因爲springboot使用的是內置tomcat,所以我這邊選擇tomcat文件,在resources目錄下導入xxx.jks
4.接下來配置properties文件,密碼在同文件夾的keystorePass.txt中(騰訊雲)
5.個人比較喜歡yml格式,簡潔直觀(阿里雲)
6.到這個時候基本配置完成,但不能使用https後就通知所有人重新保存網址,這時候就需要增加請求轉發,自動從http轉到https
寫法一:在啓動類也就是@SpringBootApplication註解類中加上使用
/** * http重定向到https * @return */ @Bean public TomcatServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint constraint = new SecurityConstraint(); constraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); constraint.addCollection(collection); context.addConstraint(constraint); } }; tomcat.addAdditionalTomcatConnectors(httpConnector()); return tomcat; } @Bean public Connector httpConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); //Connector監聽的http的默認端口號 connector.setPort(8080); connector.setSecure(false); //監聽到http的端口號後轉向到的https的端口號,也就是項目配置的port connector.setRedirectPort(8089); return connector; }
寫法二:另外新建一個配置類,加上@Configuration註解聲明
@Configuration public class TomcatConfig { @Bean TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() { TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(){ @Override protected void postProcessContext(Context context) { SecurityConstraint constraint = new SecurityConstraint(); constraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); constraint.addCollection(collection); context.addConstraint(constraint); } }; factory.addAdditionalTomcatConnectors(createTomcatConnector()); return factory; } private Connector createTomcatConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(5001); connector.setSecure(false); connector.setRedirectPort(443); return connector; } }
7.現在可以通過https://域名:8089/index訪問,這樣就看到熟悉的小鎖了
8.通過域名訪問失敗原因及解決辦法
- 域名未配置解析,去域名管理配置解析,10分鐘後通過ping 域名看是否顯示ip,顯示則解析成功!
- 域名未認證,去域名管理上傳個人信息進行域名實名!
- 域名已實名但未網站未備案,解決辦法
- 去進行網站實名,使用騰訊雲小程序認證進行icp備案即可!
- 可以通過域名訪問但必須加上自定義端口才行,不能使用8080或443等默認端口,否則提示連接已重置!