Skip to content

Instantly share code, notes, and snippets.

@konklone
Last active January 2, 2024 15:09
Show Gist options
  • Star 39 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save konklone/9968713 to your computer and use it in GitHub Desktop.
Save konklone/9968713 to your computer and use it in GitHub Desktop.
Force a quick redirect to HTTPS on Github Pages for your domain (and only your domain)
<script>
var host = "YOURDOMAIN.github.io";
if ((host == window.location.host) && (window.location.protocol != "https:"))
window.location.protocol = "https";
</script>
@sanikkenway
Copy link

@hakatashi thanks, saves me the hassle

@JCarlosR
Copy link

JCarlosR commented Dec 7, 2016

@mikeumus "Always uses https" is equivalente to the 301 redirects?
Here is a tutorial about that: https://rck.ms/jekyll-github-pages-custom-domain-gandi-https-ssl-cloudflare/

@yowainwright
Copy link

@mikeumus worked AWESOMELY!!! ~THANK YOU!!!

@englishextra
Copy link

englishextra commented Jun 18, 2017

You must check for http and NOT for https

bad:

window.location.protocol != "https:"

safe:

window.location.protocol === "http:"

Why? Because in webapps wrapped in Electron and NWjs there's no http - it's file: and chrome-extension:

So:

/*global window */
/*jslint browser: true */
(function (root) {
	"use strict";
	var h = root ? root.location.hostname : "",
	p = root ? root.location.protocol : "";
	if ("http:" === p && !(/^(localhost|127.0.0.1)/).test(h)) {
		root.location.protocol = "https:";
	}
}
	("undefined" !== typeof window ? window : this));

@infinitbility
Copy link

In this article, explain how to work HTTPS URL for your custom domain if you are using cloudflare.

https://infinitbility.com/always-use-https-url-using-cloudflare

@drortirosh
Copy link

shorter condition:

 if (window.location.href.match("http://MYDOMAIN")) window.location.protocol='https:'

Note that the MYDOMAIN can even be partial (e.g. to support both domain.github.io, domain.com, whatever) or use more complex regex matching. The important thing is to avoid the test domains (http://localhost, http://127.0.0.1, etc)

@Pravardhitha
Copy link

but where should i add the code. into my index.html?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment