Recent versions of Apache and Let's Encrypt redirect to https automatically making this script unnecessary. If Apache is not redirecting to https try this script.
This is code to redirect web page traffic from http to https ( secure web )
To reference this javascript file use the following in the head of your webpages
<script src="./redirectToHttps.js"></script>
Then place the redirectToHttps.js file in the same directory as the file(s) with the script tag or adjust the src location.