This time I will show you how to deploy HTTPS in Node.js. What are the precautions for deploying HTTPS in Node.js? The following is a practical case, let's take a look.
With the rapid development of the Internet, Internet information security has attracted more and more attention.HTTPS should be one of the technologies that major manufacturers have been trying to popularize in the past two years. Major domestic manufacturers have basically fully popularized HTTPS.
Node.js How to deploy free
HTTPS and simple deployment
HTTP/ 2.
HTTPS Certificate Services.
Services provided by ISRG (Internet Security Research Group, Internet Security Research Group), free, fast access, stable, etc.So the certificate deployed this time also revolves around
Let's Encrypt.
To deploy Let's Enctrypt certificate, you only need to introduce this package and use it:
- Automatic registration
Let's Encrypt
Certificate
- Automatic renewal (about 80 days), and the server does not need to be restarted
- Supports # #And
The related certificate ecosystem is very complete, and there is also greenlock-koa that supports koa
. Installation and use
Install via
npmgreenlock-express
:<pre class="brush:php;toolbar:false">$ npm install --save greenlock-express@2.x</pre>
It’s very simple to use, it’s
The demo provided by default: <pre class="brush:php;toolbar:false">const greenlock = require('greenlock-express')
require('greenlock-express').create({
// 测试
server: 'staging',
// 联系邮箱
email: 'john.doe@example.com',
// 是否同意 Let's Encrypt 条款... 这必须为 true 啊,不然走不下去
agreeTos: true,
// 申请的域名列表,不支持通配符
approveDomains: [ 'tasaid.com', 'www.tasaid.com' ],
// 绑定 express app
app: require('express')().use('/', function (req, res) {
res.end('Hello, World!');
})
}).listen(80, 443)</pre>
The certificate exists
. Of course the above code can only be used in the test/development environment, because it does not apply for a valid certificate, but generates a self-signed certificate (the same as the previous 12306 self-signed certificate), which is used Debugging in a development environment.
API
greenlock-express’s create(options)
Function parameters
are signed as follows: interface Options {
/**
* Express app
*/
app: Express
/*
* 远程服务器
* 测试环境中可用为 staging
* 生产环境中为 https://acme-v01.api.letsencrypt.org/directory
*/
server: string
/**
* 用于接收 let's encrypt 协议的邮箱
*/
email: string
/**
* 是否同意协议
*/
agreeTos: boolean
/**
* 在注册域名获取证书前,会执行这个回调函数
* string[]: 一组需要注册证书的域名
* 函数: 第一个参数跟 Options 格式差不多,第二个参数是当前自动获取的域名信息,第三个参数是在处理完之后传递的回调函数
*/
approveDomains: string[] | (opts, certs: cb) => any
/**
* 更新证书最大天数 (以毫秒为单位)
*/
renewWithin: number
/**
* 更新证书的最小天数(以毫秒为单位)
*/
renewBy: number
}
After testing, in a real production environment,
must be a function, and passing an array will not take effect. Production environment
Deployment in the production environment also requires some configuration changes and the introduction of some packages.
Update package:
$ npm i --save greenlock-express@2.x $ npm i --save le-challenge-fs $ npm i --save le-store-certbot $ npm i --save redirect-https
Production code:
const greenlock = require('greenlock-express') const express = require('express') const app = express() const lex = greenlock.create({ // 注意这里要成这个固定地址 server: 'https://acme-v01.api.letsencrypt.org/directory', challenges: { 'http-01': require('le-challenge-fs').create({ webrootPath: '~/letsencrypt/var/acme-challenges' }) }, store: require('le-store-certbot').create({ webrootPath: '~/letsencrypt/srv/www/:hostname/.well-known/acme-challenge' }), approveDomains: (opts: any, certs: any, cb: any) => { appLog.info('approveDomains', { opts, certs }) if (certs) { /* * 注意这里如果是这样写的话,一定要对域名做校验 * 否则其他人可以通过将域名指向你的服务器地址,导致你注册了其他域名的证书 * 从而造成安全性问题 */ // opts.domains = certs.altnames opts.domains = [ 'tasaid.com', 'www.tasaid.com' ] } else { opts.email = '你的邮箱@live.com' opts.agreeTos = true } cb(null, { options: opts, certs: certs }) }, }) // 这里的 redirect-https 用于自动将 HTTP 请求跳到 HTTPS 上 require('http').createServer( lex.middleware( require('redirect-https')() ) ).listen(80, function () { console.log('Listening', `for ACME http-01 challenges on: ${JSON.stringify(this.address())}`) }) // 绑定 HTTPS 端口 require('https').createServer( lex.httpsOptions, lex.middleware(app) ).listen(443, function () { console.log(('App is running at http://localhost:%d in %s mode'), app.get('port'), app.get('env')) console.log('Press CTRL-C to stop\n') })
If it does not take effect, you can check the certificate information of
~/letsencrypt and whether port 443 is correct Open. Deploying HTTP/2
HTTP/2 is an upgraded version of HTTP/1.1, which mainly improves the following aspects:
- Binary protocol: Using binary streams
- Multiplexing: Multiplexing pipelines for one request
服务器推送:解决 HTTP/1.x 时代最大的痛点
值的注意的是,HTTP/2 是支持 HTTP 协议的,只不过浏览器厂商都不愿意支持 HTTP,所以基本上可以认为,用上 HTTP/2 的前置条件是必须部署 HTTPS。
SPDY
早在 2009 年,Google 开发了一个实验性协议,叫做 SPDY,目的解决 HTTP/1.x 中的一些设计缺陷。在 SPDY 发布几年后,这个新的实验性协议得到了 Chrome、Firefox 和 Opera 的支持,应用越来越广泛。然后 HTTP 工作组 (HTTP-WG) 在这个 SPDY 的基础上,设计了 HTTP/2,所以可以说 SPDY 是 HTTP/2 的前身。
关于 HTTP/2 的详情可以参考 这篇文章。
部署 HTTP/2
引入 HTTP/2
在 Node.js
中也十分简单,只需要引入 spdy
包即可:
$ npm i --save spdy
然后我们把上一节的代码做一点修改即可支持 HTTP/2:
const greenlock = require('greenlock-express') const express = require('express') // HTTP/2 const spdy = require('spdy') const app = express() const lex = greenlock.create({ // 注意这里要成这个固定地址 server: 'https://acme-v01.api.letsencrypt.org/directory', challenges: { 'http-01': require('le-challenge-fs').create({ webrootPath: '~/letsencrypt/var/acme-challenges' }) }, store: require('le-store-certbot').create({ webrootPath: '~/letsencrypt/srv/www/:hostname/.well-known/acme-challenge' }), approveDomains: (opts: any, certs: any, cb: any) => { appLog.info('approveDomains', { opts, certs }) if (certs) { /* * 注意这里如果是这样写的话,一定要对域名做校验 * 否则其他人可以通过将域名指向你的服务器地址,导致你注册了其他域名的证书 * 从而造成安全性问题 */ // opts.domains = certs.altnames opts.domains = [ 'tasaid.com', 'www.tasaid.com' ] } else { opts.email = '你的邮箱@live.com' opts.agreeTos = true } cb(null, { options: opts, certs: certs }) }, }) // 这里的 redirect-https 用于自动将 HTTP 请求跳到 HTTPS 上 require('http').createServer( lex.middleware( require('redirect-https')() ) ).listen(80, function () { console.log('Listening', `for ACME http-01 challenges on: ${JSON.stringify(this.address())}`) }) // HTTP/2 spdy.createServer(lex.httpsOptions, lex.middleware(app)).listen(443, function () { console.log('Listening https', `for ACME tls-sni-01 challenges and serve app on: ${JSON.stringify(this.address())}`) })
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to deploy HTTPS in Node.js. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment