本文用于记录购买了腾讯云服务器、域名之后,如何将域名绑定到服务器,如何申请证书来提供https服务。
一、域名解析
在我的域名中找到购买的域名:console.cloud.tencent.com/domain/all-…
如上图,我购买了一个域名,点击域名记录右边的解析,进入下图的域名绑定,根据提示,一般主机记录填写www,记录值填写你的云服务器的ip值,这样,这个域名的所有访问都会转移到这台服务器上了。
二、绑定https
以一个简单的node代码为例,演示下如何使用。如下代码是一段简单的nodejs代码,用于启动一个程序监听8888端口,正常来说,根据代码逻辑,启动后在浏览器里使用ip:8888/flower,代码运行匹配/flower路径就可以拿到index.html文件展示了。
// 启动https服务需要https包
// 读取文件需要fs包
const https = require('https');
const fs = require('fs');
// 将两个证书文件读取放到options对象中
// 使用readFileSync()方法,顺序地执行读文件和启动服务操作
const options = {
key: fs.readFileSync('/home/ubuntu/cert/picframe.xyz_nginx/picframe.xyz.key'),
cert: fs.readFileSync('/home/ubuntu/cert/picframe.xyz_nginx/picframe.xyz_bundle.crt')
};
var path = require('path');
https.createServer(options, function (req, res) {
const url = req.url;
let fpath = '';
console.log("url: " + url);
if (url === '/flower') {
// 展示烟花
fpath = path.join(__dirname, './index.html')
}
if (fpath === '') {
return res.end('404 Not found');
}
// 以字节形式读取
fs.readFile(fpath, (err, dataBuffer) => {
if (err) {
res.statusCode = 404
return res.end('404 Not found')
}
res.write(dataBuffer)
res.end()
})
}).listen(8888, '0.0.0.0');
https包主要是需要证书,在上面代码中,主要是需要设置证书文件
const options = {
key: fs.readFileSync('/home/ubuntu/cert/picframe.xyz_nginx/picframe.xyz.key'),
cert:fs.readFileSync('/home/ubuntu/cert/picframe.xyz_nginx/picframe.xyz_bundle.crt'),
};
打开腾讯云我的证书页面:console.cloud.tencent.com/ssl
有很多付费的证书方式,可以用于自动接入等等,但这里我们是直接在代码里面指定证书的,这种是手动接入,先申请个免费证书就可以了。在其中绑定自己购买的域名。
申请完成后,回到我的证书页面下载,有很多证书文件下载,一般下载Nginx类型就可以了,我们之前那段nodejs代码需要的就是crt文件和key文件。