Koa.js middleware to enforce HTTPS connection on any incoming requests.In case of a non-encrypted HTTP request, koa-sslify automatically redirects to an HTTPS address using a 301 permanent redirect
(or optionally 307 Temporary Redirect
).
Koa SSLify can also work behind reverse proxies (load balancers) like on Heroku, Azure, GCP Ingress etcand supports custom implementations of proxy resolvers.
$ npm install --save koa-sslify
Importing default factory function:
const sslify = require('koa-sslify').default; // factory with default options
const Koa = require('koa');
app = new Koa();
app.use(sslify());
Default function accepts several options.
Name | Type | Default | Description |
---|---|---|---|
resolver |
Function | httpsResolver |
Function used to test if request is secure |
hostname |
Function | undefined |
Function that takes the request hostname string as its only argument and returns the desired hostname to use as a result. Uses request hostname if not set or return value is falsy |
port |
Integer | 443 |
Port of HTTPS server |
ignoreUrl |
Boolean | false |
Ignore url path (redirect to domain) |
temporary |
Boolean | false |
Temporary mode (use 307 Temporary Redirect) |
skipDefaultPort |
Boolean | true |
Avoid :443 port in redirect url |
redirectMethods |
Array | ['GET', 'HEAD'] |
Whitelist methods that should be redirected |
disallowStatus |
Integer | 405 |
Status returned for dissalowed methods |
Resolver is a function from classic Koa ctx
object to boolean.This function is used to determine if request is or is not secured (true means is secure).Middlware calls this function and based on its returned value either passescontrol to next middleware or responds to the request with appropriate redirect response.
There are several resolvers provided by this library but it should be very easy to implementany type of custom check as well.
for instance, Heroku has a reverse proxy that uses x-forwarded-proto
header.This is how you can configure app with this resolver:
const {
default: sslify, // middleware factory
xForwardedProtoResolver: resolver // resolver needed
} = require('koa-sslify');
const Koa = require('koa');
app = new Koa();
// init middleware with resolver
app.use(sslify({ resolver }));
Those are all resolver provided by default:
Name | Used by | Example |
---|---|---|
httpsResolver |
Node.js server running with tls support | sslify() |
xForwardedProtoResolver |
Heroku, Google Ingress, Nodejitsu | sslify({ resolver: xForwardedProtoResolver }) |
azureResolver |
Azure | sslify({ resolver: azureResolver }) |
customProtoHeaderResolver |
any non-standard implementation (Kong) | sslify({ resolver: customProtoHeader('x-protocol') }) |
forwardedResolver |
standard header | sslify({ resolver: forwardedResolver }) |
Some additional information about reverse proxies:
Heroku, nodejitsu, GCE Ingress and other hosters often use reverse proxies which offer SSL endpointsbut then forward unencrypted HTTP traffic to the website.This makes it difficult to detect if the original request was indeed via HTTPS. Luckily,most reverse proxies set the x-forwarded-proto
header flag with the original request scheme.
Azure has a slightly different way of signaling encrypted connections.It uses x-arr-ssl
header as a flag to mark https traffic.
If you're still in a situation where you need to use custom resolver you can implement it as for example following:
const { default: sslify } = require('koa-sslify');
app.use(sslify({
resolver: (ctx) => ctx.request.header['x-is-secure'] === 'yup!'
}))
Contributions to increase coverage of default resolvers are welcomed.
Those are full example apps using Koa SSLify to enforce HTTPS.
This example starts 2 servers for app.
const Koa = require('koa');
const http = require('http');
const https = require('https');
const fs = require('fs');
const { default: enforceHttps } = require('koa-sslify');
const app = new Koa();
// Force HTTPS using default resolver
app.use(enforceHttps({
port: 8081
}));
// index page
app.use(ctx => {
ctx.body = "hello world from " + ctx.request.url;
});
// SSL options
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
}
// start the server
http.createServer(app.callback()).listen(8080);
https.createServer(options, app.callback()).listen(8081);
This example starts a single http server which is designed to run behinda reverse proxy like Heroku.
const Koa = require('koa');
const {
default: enforceHttps,
xForwardedProtoResolver: resolver
} = require('koa-sslify');
var app = new Koa();
// Force HTTPS via x-forwarded-proto compatible resolver
app.use(enforceHttps({ resolver }));
// index page
app.use((ctx) => {
ctx = "hello world from " + ctx.request.url;
});
// proxy will bind this port to it's 443 and 80 ports
app.listen(3000);
By default only GET
and HEAD
methods are whitelisted for redirect.koa-sslify will respond with 405
with appropriete Allow
header by default.You can change whitelisted methods by passing redirectMethods
array to optionsas well as change status for disallowed methods using disallowStatus
.
By default port is excluded from redirect url if it's set to 443
.Since 443
is default port for HTTPS
browser will use it by default anyway so thereis no need to explicitly return it as part of URL. Anyway in case you need to always return port as part of URL stringyou can pass options with skipDefaultPort: false
to do the trick.
MIT
This project is heavily inspired by Florian Heinemann's express-sslifyand Vitaly Domnikov's koa-force-ssl.
第三章:node+koa2后端服务搭建框架 目录: 1、安装本地、服务器环境(node、npm、git) 2、通过uni-app+vue搭建项目框架 3、node+koa2后端服务搭建框架 4、mysql安装与配置,快速写入数据库(MySQL Workbench 8.0 CE) 5、阿里云服务器(全套保姆级)配置篇 6、nginx配置代理篇(优雅的解决各种代理问题【推荐使用】) 7、iis配置与挂
// 引入https 以及 koa-ssl const https = require('https') const sslify = require('koa-sslify').default var fs= require("fs"); // 路径为证书放置的位置 const options = { key: fs.readFileSync('./httpskey/0_xcx.gu
var https=require(“https”);//https服务 var fs= require(“fs”); var Koa = require(‘koa’); var enforceHttps = require(‘koa-sslify’).default; var app = new Koa(); app.use(enforceHttps()); var options = { ke
第一步 生成或购买证书 我使用的是阿里云提供的证书服务,购买的是免费证书 进入阿里云->安全(云盾)->证书服务 即可购买证书了 如果只是本地测试,可以用JDK自带的keytool生成自己的证书。可以参考: 1. JDK自带工具keytool生成ssl证书 2. 如何利用keytool工具生成数字证书_百度经验 最终我们得到xxxx.key和xxxx.pem文件 第二步 搭建HTTPS服务 con
这两天上线刚备案好的网站,但是用了服务器提供商的一键HTTPS服务,方便的地方是可以强制http转https,比如首页登录http://XXX.com,会自动跳转到https://XXX.com。 但是发现无法通过域名加端口号访问其他端口。因为打算3000端口是用作api的。 后来发现不用一键https服务,换成正常的dns解析,其他端口就可以正常通过域名+端口号访问了。 但是依然想http网站首
目录 背景 https通信 https证书 编程 背景 前面已经讲解过了KOA的基础编程技巧。但是都是基于http的通信,现在讲究安全,而最简单的安全手段就是https。KOA如何实现呢? https通信 KOA实现https通信需要依赖几个包: https koa-sslify fs 分别安装。 https证书 证书是这个环节里头最麻烦的动作,企业开发的话,公司都会提供给你企业的证书。 需要注意
因为某浏览器请求https网站的时候,请求http接口是错误的,浏览器会报出协议不一致的错误.net::ERR_SSL_PROTOCOL_ERROR,接口就必须走https协议了 一. 安装https、koa-sslify、fs库 npm i -S https fs koa-sslify app.js中引入koa-sslify const sslify = require('koa-sslify'
Koa art-template view render middleware. support all feature of art-template. Install npm install --save art-template npm install --save koa-art-template Example const Koa = require('koa'); const ren
koa是Express的下一代基于Node.js的web框架,目前有1.x和2.0两个版本。 历史 1. Express Express是第一代最流行的web框架,它对Node.js的http进行了封装,用起来如下: var express = require('express'); var app = express(); app.get('/', function (req, res) {
Koa 是下一代的 Node.js 的 Web 框架。由 Express 团队设计。旨在提供一个更小型、更富有表现力、更可靠的 Web 应用和 API 的开发基础。 Koa可以通过生成器摆脱回调,极大地改进错误处理。Koa核心不绑定任何中间件,但提供了优雅的一组可以快速和愉悦地编写服务器应用的方法。 示例代码: var koa = require('koa');var app = koa();//
Koa - HelloWorld 以上便是全部了,我们重点来看示例,我们只注册一个中间件, Hello Worler Server: <?php $app = new Application(); // ... $app->υse(function(Context $ctx) { $ctx->status = 200; $ctx->body = "<h1>Hello Worl
koa-log4js A wrapper for log4js-node which support Koa logger middleware.Log message is forked from Express (Connect) logger file. Note This branch is use to Koa v2.x.To use Koa v0.x & v1.x, please ch
koa-rudy 环境 node -v >=6.9.0pm2 启动 npm install npm run dev 开发环境 npm run dev || test || prod 接口测试 npm run mocha 推荐开发工具 vscode 实现 支持 async/await MVC架构(middleware-view-controller) RESTful a
学习 koa 源码的整体架构,浅析koa洋葱模型原理和co原理 1. 前言 你好,我是若川,微信搜索「若川视野」关注我,专注前端技术分享。欢迎加我微信ruochuan12,加群交流学习。 这是学习源码整体架构系列第七篇。整体架构这词语好像有点大,姑且就算是源码整体结构吧,主要就是学习是代码整体结构,不深究其他不是主线的具体函数的实现。本篇文章学习的是实际仓库的代码。 本文仓库地址:git clon
koa-seo SEO middleware for koa base on chrome-render, a substitute for prerender. Modern web app use technique like react.js vue.js which render html in browser, this lead to search engine can't crawl