1. Home »
  2. Tech

Convert all HTTP links to HTTPS using JavaScript


In some cases you may need to use JavaScript to convert all instance of links from HTTP to HTTPS. You will need such code only in case the user is visiting your website using a secure connection SSL/TLS. This practice will mainly be used in sites that allow multi protocol (secure and non-secure). This is not the best practice to maintain a secure connection for your visitors as it is better to make the source code renders with HTTPS links.

This code is a JavaScript code that depends mainly on jQuery so you must load the jQuery library first by inserting the following code in your <head> section and make sure it is in the very beginning so that it will be the first script to load.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

Then make sure you add the following code just after the beginning of your <body> tag to convert all instance of anchor tags with http to https. Also make sure to edit the code by changing yourdomain with your actual site domain.

<script type="text/javascript">
$(document).ready(function(e) {
if (document.location.protocol === 'https:') {
      this.href = this.href.replace("http://www.yourdomain.com",