Normal HTTP services are not encrypted, and the transmitted data can be easily accessed by others. HTTPS uses encrypted transmission and has higher security. Now more and more websites use HTTPS services. However, HTTPS is a bit more difficult to start than HTTP.

The following backend framework is used as an example to enable the HTTPS service.

1. OpenSSL generates a certificate

The installation method of OpenSSL is omitted here, please go to the search engine to check.

After the installation, use OpenSSL to generate HTTPS certificates.

openssl genrsa -des3 -out server.key 2048
Copy the code

Generate server. The key. You need to set a password to generate it.

openssl rsa -in server.key -out server.key
Copy the code

Convert server.key to a password-free version

openssl req -new -x509 -key server.key -out ca.crt -days 3650
Copy the code

Generate ca.crt. This step and the following step will ask you to enter some information. The common name should correspond to the domain name (if there is one).

openssl req -new -key server.key -out server.csr
Copy the code

Generate server. The CSR

openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey server.key -CAcreateserial -out server.crt
Copy the code

Finally, generate server. CRT, which is the certificate we need

2. An egg. Js configuration

Add the certificate path to the configuration:

const path = require('path');  config.cluster = {  https: {    key: path.join(appInfo.baseDir, 'httpskey/server.key'),    cert: path.join(appInfo.baseDir, 'httpskey/server.crt'),  },};
Copy the code

Then start the service is OK!

When we visit the website, we will be prompted that the website is not secure because our certificate is self-signed and cannot be trusted. At this time, we can ignore the prompt and still visit the website.

Note that some tutorials say that HTTPS has port 443, and some of you will set it to that port. However, after the setting, the access is unavailable. Other port numbers do not have this problem.

Setting port number to 443