Skip to content

Commit

Permalink
Redirect from http to https
Browse files Browse the repository at this point in the history
  • Loading branch information
kimjoar committed Jul 6, 2017
1 parent 82360c4 commit 6e415ce
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/server/config/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export default () => Joi.object({
basePath: Joi.string().default('').allow('').regex(/(^$|^\/.*[^\/]$)/, `start with a slash, don't end with one`),
ssl: Joi.object({
enabled: Joi.boolean().default(false),
redirectHttpFromPort: Joi.number(),
certificate: Joi.string().when('enabled', {
is: true,
then: Joi.required(),
Expand Down
2 changes: 2 additions & 0 deletions src/server/http/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { handleShortUrlError } from './short_url_error';
import { shortUrlAssertValid } from './short_url_assert_valid';
import shortUrlLookupProvider from './short_url_lookup';
import setupConnectionMixin from './setup_connection';
import setupRedirectMixin from './setup_redirect_server';
import registerHapiPluginsMixin from './register_hapi_plugins';
import xsrfMixin from './xsrf';

Expand All @@ -17,6 +18,7 @@ export default async function (kbnServer, server, config) {

const shortUrlLookup = shortUrlLookupProvider(server);
await kbnServer.mixin(setupConnectionMixin);
await kbnServer.mixin(setupRedirectMixin);
await kbnServer.mixin(registerHapiPluginsMixin);

// provide a simple way to expose static directories
Expand Down
40 changes: 40 additions & 0 deletions src/server/http/setup_redirect_server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { format as formatUrl } from 'url';
import Hapi from 'hapi';

// If a redirect port is specified, we need to start a server a non-ssl
// server at this port, and redirect all requests to the ssl port.
export default function (kbnServer, server, config) {
const isSslEnabled = config.get('server.ssl.enabled');
const portToRedirectFrom = config.get('server.ssl.redirectHttpFromPort');

// Both ssl and port to redirect from must be specified
if (!isSslEnabled || portToRedirectFrom === undefined) {
return;
}

const host = config.get('server.host');
const sslPort = config.get('server.port');

const redirectServer = new Hapi.Server();

redirectServer.connection({
host,
port: portToRedirectFrom
});

redirectServer.ext('onRequest', (req, reply) => {
reply.redirect(formatUrl({
protocol: 'https',
hostname: host,
port: sslPort,
pathname: req.url.pathname,
search: req.url.search,
}));
});

redirectServer.start((err) => {
if (err) {
throw err;
}
});
}

0 comments on commit 6e415ce

Please sign in to comment.