I'm attempting to redirect www to non-www for both HTTP and HTTPS requests. My root .htaccess looks like this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteRule ^(.*)$ http://example.com/$1 [R=301]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{SERVER_PORT} ^443
RewriteRule ^(.*)$ https://example.com/$1 [R=301]
This isn't fully working as expected. What happens:
Visiting http://www.example.com
results in a redirect to http://example.com
. This indicates my first rule and condition are working, the mod_rewite module is hunky-dory and .htaccess is enabled OK.
Visiting https://www.example.com
doesn't result in a redirect. I remain on https://www.example.com
My question
In order for the above rewrite rules to work, must my server have an SSL certificate? It currently doesn't and I'm wondering if that is the reason things aren't working.
Perhaps you could try the following:
RewriteEngine on
# Check if the host contains "www."
RewriteCond %{HTTP_HOST} ^www\.
# Check if we're using HTTPS
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
# Redirect accordingly
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With