Forcing Resources to HTTPS for Better Security via htaccess

If you are running a website be it a personal blog or corporate website, most browsing client like Chrome and Mozilla are requiring you to use a secure web protocol HTTPS. Moreover, Google will be giving priority to those sites that are already in HTTPS from Search Engine Optimisation aspect.

Amending your website resources to use a secure protocol is a bit tricky but this article will guide you to do some tricks in Apache configs in .htaccess file.

The regex codes below are using mod_substitute apache module:

This will find links for href attributes and substitute url value

Substitute "s|(href[^http://]+)(?<=['\"])http(?=://)|$1https|"

This will look for src attributes particularly images, JS scripts and replace the url value

Substitute "s|(src[^http://]+)(?<=['\"])http(?=://)|$1https|"

Find forms and look for action attributes and replace url value

Substitute "s|(action[^http://]+)(?<=['\"])http(?=://)|$1https|"

I may gonna miss some other resources and other points, just feel free to comment below. Also for those resources that are using DOM, you can also use a jQuery to modify it e.g. when the document is loading modify links that are generated by DOM.

In Google Chrome, You may encounter this warning dialog,

Mixed Content: The page at ‘https://www.your-website.com/’ was loaded over HTTPS, but requested an insecure image ‘http://www.your-website/wp-content/uploads/2019/08/image1.png’. This content should also be served over HTTPS.


This indicates that if you are using HTTPS protocol, all resources that are generated to load a web page or even the entire website must also be in HTTPS. E.g. <img src=”HTTPS://www.your-website.com/wp-content/uploads/2019/08/image-1.png” />

There are also other ways to modify all linked resources. One of those is to programatically modify the server-side code that is responsible for printing the HTML view. This article is only discussing about altering the website resources by editing the .htaccess an Apache config file to run the server where you can do some logic and derivatives.

You can also check a jQuery code to modify links resources that is loaded using DOM.

If you have a better way to do a regex modification for all links, please comment below.

Forcing Resources to HTTPS for Better Security via htaccess1.67/5 (33.33%) 3 votes
About

Elvin is one of the contributors of InnoveDesigns.com. He has been creating Wordpress Plugins, Magento Extensions, & Mobile Applications. If you find this article useful, please Follow him on .

Published under Web Development Guide