For some reason I need to keep both http and https versions of my site. I am using wordpress. Can I add a rel=canonical for https version through the .htaccess? What is the easiest way to avoid duplicate content?
Just set the canonical to the (preferred) HTTPS version. Both HTTP and HTTPS will still be available. Google will likely favour the HTTPS version over HTTP anyway, regardless of what protocol you set in the
rel="canonical" tag (because it will presumably know that both HTTPS and HTTP are available).
Setting the canonical conditionally based on the protocol doesn't make sense - both HTTP and HTTPS are presumably serving the same content? You can't have two different "canonical URLs" for the same content.
UPDATE: If there is a code to set it using htaccess, please just let me know.
Whilst you can technically set the canonical URL by returning the appropriate
Link: HTTP response header using mod_headers in
.htaccess like this:
Header add Link "<https://example.com/url-path-to-page-goes-here>; rel=\"canonical\""
...I don't see how, on a WordPress site (or any site controlled by a CMS) you know what the canonical URL should be at the time
.htaccess executes in order to be able to set the correct canonical URL? (Unless, perhaps, there is a specific URL pattern you follow? But this is not stated in your question.)
In my opinion, this needs to be done in WordPress, since only WordPress knows what the canonical URL should be.