最近在学习微信小程序,小程序开发使用的所有接口都必须是
https
的,因此本文主要将服务器如何配置https(以阿里云ECS共享型 n4
云服务器为例)
一、域名申请(需要购买)
控制台 -> 域名 -> 域名注册 -> 选择域名,按页面提示输入相关信息 -> 等待实名认证通过
申请免费ssl证书步骤如下:
二、申请ssl证书(有免费证书)
ssl证书控制台 -> 申请免费证书 -> 按页面提示,填入相关信息 -> 验证信息 -> 等待验证通过
等验证通过后,就可以下载ssl证书
了
三、nginx配置https
- 进入nginx的配置文件:
cd /etc/nginx
; - 将证书上传至服务器,我上传到
/etc/nginx/cert
- 修改
nginx.conf
文件:include /etc/nginx/conf.d/ssl.conf
- /etc/nginx/conf.d/ssl.conf文件
server {
listen 8081; # nginx配置端口,这里我是8081
server_name localhost;
# 配置http访问自动转发到https
rewrite ^(.*) https://$host$1 permanent;
}
server {
listen 443 ssl;
server_name _; # 值为 _ 表示 域名和ip都能访问
ssl_certificate "/etc/nginx/cert/server.pem"; # ssl的.pem文件(绝对地址)
ssl_certificate_key "/etc/nginx/cert/server.key"; # ssl的.key文件(绝对地址)
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
# 配置文件上传大小
client_max_body_size 2G;
location / {
root /usr/local/develop/web-front-end;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /apis/ {
# rewrite ^.+iot/?(.*)$ /$1 break;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers "Accept, X-Token, Content-Type";
add_header Access-Control-Allow-Methods "GET, POST, DELETE, PATCH, PUT, OPTIONS";
proxy_pass http://localhost:13666/;
# (以下2句)配置允许创建websocket
# proxy_set_header Upgrade websocket;
# proxy_set_header Connection Upgrade;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
设置安全组规则
到这就可以通过ip访问了
本地使用域名也能访问
修改本地电脑的hosts文件:C:\Windows\System32\drivers\etc\host
四、node配置https
在项目根目录下新建cert空文件夹,把ssl证书(.pem文件、.key文件)复制到cert文件夹中;
var app = express();
var https = require('https');
var fs = require('fs');
var path = require('path');
/* 服务启动监听 */
var privateCrt = fs.readFileSync(path.join(process.cwd(), 'cert/server.pem'), 'utf8');
var privateKey = fs.readFileSync(path.join(process.cwd(), 'cert/server.key'), 'utf8');
const HTTPS_OPTOIN = {
key: privateKey,
cert: privateCrt
};
const SSL_PORT = 13666;
const httpsServer = https.createServer(HTTPS_OPTOIN, app);
httpsServer.listen(SSL_PORT, () => {
console.log(`HTTPS Server is running on: https://localhost:${SSL_PORT}`);
});
遗留问题
- 阿里云域名备案