前言
問題描述:怎么讓springboot部署在服務器上使用https協議方式訪問我們的接口或者域名,目的是某些平台請求的是https協議,而不是https
部署環境:阿里雲 centos7服務器,springboot項目打包的jar,nginx反向代理
注:部署前需要解決幾個問題
1)需要配置springboot項目支持https協議,
2)需要配置阿里雲的安全組,放行相關的端口,如本文中開放的8080和8081端口
3)配置nginx的nginx.conf文件做好反向代理
4)申請ssl文件,至於怎么申請ssl文件自行百度(注:因為springboot啟動項目的時候使用的是tomcat,我們部署的時候需要nginx做好反向代理,所以這里面我們需要兩個類型的ssl文件,即nginx下面的xxx.pem/xxx.key和tomcat下面的xxx.pfx/xxx.txt文件,xxx.txt里面保存的是密碼)
(圖1)
(圖2)
5)把申請的ssl里面的pfx文件方向項目的根目錄下,如下圖
步驟:
1.配置本地項目xxx.yml文件,如下圖
相關的代碼如下
server:
servlet:
#配置訪問的項目路徑
context-path: /
#配置HTTPS訪問端口
port: 8443
ssl:
enabled: true
key-store: xxx.pfx
key-store-password: 123456
#配置http訪問端口
http:
port: 8080
2.配置啟動項,即在啟動項里面增加如下代碼,這里可以配置通知支持http和https
import org.apache.catalina.connector.Connector;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@MapperScan(value = "xxx.mapper")
public class SitecloudApplication {
public static void main(String[] args) {
SpringApplication.run(SitecloudApplication.class, args);
}
// springboot2 寫法
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(createStandardConnector()); // 添加http
return tomcat;
}
// 配置http
private Connector createStandardConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(8080);//nginx需要代理的端口,這里我直接寫固定了,這里的端口是yml文件中的8080端口,你可以直接取yml文件的端口
return connector;
}
}
3.配置阿里雲的安全組,放行相關的端口
4.配置nginx
進入你安裝的nginx目錄里面xxx/conf/nginx.conf文件中,配置如下
#https支持
server {
listen 443 ssl;
server_name 你的域名不需要在前面加http;
ssl on;
ssl_certificate /ssl/xxx.pem;
ssl_certificate_key /ssl/xxx.key;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
location /images/{
root /usr/;
autoindex on;
}
location /app {
root html;
index index.html index.htm;
proxy_pass http://ip:8080;
}
}
server {
listen 80;
server_name 你的域名不需要在前面加http;
rewrite ^(.*)$ https://$host$1 permanent;
}
}
5.springboot本地打成xxx.jar文件,放入在linux中你新建的任何文件夾中
6.把你申請的ssl的xxx.pfx,xxx.pem,xxx.key文件放在和你的jar一個目錄的地方
7.運行java -jar xxx.jar
8.在nginx的sbin文件夾下啟動nginx
./nginx -s reload
./nginx -t
10.訪問項目,直接用域名訪問的方式如https://xxx.com:8443
訪問http:xxx.8080
至此,項目運行成功,轉載請留下出處