preface

After the SSL certificate was configured, we could access our test domain https://www.xxx.com using HTTPS smoothly. However, when we directly entered www.xxx.com in the browser address bar, we found that we entered the HTTP website. This is not consistent with our original intention.

why

Since the browser uses port 80 to access domain names by default, when we use SSL certificates, the site’s port becomes 443, so when we type the url www.xxx.com directly into the browser, we get an HTTP site with port 80 instead of an HTTPS site with port 443.

The solution

There are two ways to jump from HTTP to HTTPS:

1. NginxrewriteWill request to come overhttpThe URL is just rewritten ashttps.

server { listen 80; Enter the domain name server_name www.xxx.com. # force HTTPS rewrite ^(.*) https://$server_name$1 permanent; }Copy the code

2. Use the 301 redirection modehttpRequest redirected tohttpsOn.

server { listen 80; Enter the domain name server_name www.xxx.com. Return 301 https://$host$request_uri; }Copy the code

Complete configuration

#HTTP configuration server {listen 80; Enter the domain name server_name www.xxx.com. Return 301 https://$host$request_uri; # (2) force HTTP urls to be HTTPS rewrite ^(.*) https://$server_name$1 permanent; } #SSL uses port 443 listen 443 SSL; Server_name www.xxx.com; Ssl_certificate /usr/cert/www_xxx_com.pem; Ssl_certificate_key /usr/cert/www_xxx_com.key; Ssl_session_timeout 5m; # use the type of encryption suite ssl_ciphers ECDHE - RSA - either 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 / {root /var/ WWW /mainApp; Index.html index.htm; try_files $uri $uri/ /index.html; }}Copy the code

After the above configuration is successful, execute nginx -s reload, and then you can directly enter the domain name in the browser instead of https://www.xxx.com to access the HTTPS site. Enter the domain name www.xxx.com to access the HTTPS site.