nginx configures https and implements simultaneous https and http access for Java projects

1. Download SSL certificate

I am using Alibaba Cloud's SSL certificate. This time I am using an nginx type certificate.

2. nginx configure SSL certificate

Modify nginx.conf file

server{

    listen 443 ssl; #需要去阿里云安全组开放443端口
    server_name 你的域名;
    charset utf8;
    # ssl on; 
    ssl_certificate  存放文件的路径/xxxxx.pem;
    ssl_certificate_key 存放文件的路径/xxxxx.key;
    ssl_session_timeout 5m;
    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;

    location /verify {
            root   html;
            index  index.html index.htm;
    }

}

The path content written in the server will be converted

For example

3. Project configuration https and http

The company's Java project uses springboot, which can only recognize p12 certificates, so a tool needs to be used to convert the certificates.

Tool download link: https://pan.baidu.com/s/1WKgBRoqQ0PBLrFxcZ5Q8rg

Extraction code: 5wz8

After the installation is complete, go to the current directory to complete the operation.

When clicking on the file openssl.exe, enter: pkcs12 -export -in certificate name.pem -inkey private key name.key -out changed name.p12

A password is required when generating the p12 file. It will be used in subsequent configurations. Please remember the password you entered! ! !

Pull the generated p12 file into the project (I put it in resources here)

Configure application.yml file

server:
  #此处的端口是https使用的
  port: 8080
  #此处的端口是http使用的
  http-port: 3072
#证书配置
  ssl:
    key-store-type: "PKCS12"        #指定KeyStore的实现类型
    key-store: classpath:spark.p12   #存放位置
    key-store-password: 密码         #制作证书时输入的密码

Run the project

At this point you can see that the project is running

See the effect

Project for https and http access

Control the same project through the port to implement https or http for access (operate according to project requirements)

Create TomcatServerConfig.class file

/**
 * @author: MM
 * @date: 2023-02-14 15:59
 * 同一个项目即可以实现http访问又可以通过https访问
 */
@Component
public class TomcatServerConfig implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
    @Value("${server.http-port}")
    public Integer httpPort;
    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(httpPort);
        factory.addAdditionalTomcatConnectors(connector);
    }
}

Then run the project and see the effect

Guess you like

Origin blog.csdn.net/weixin_53799443/article/details/129447964