Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting www to non-www while maintaining the protocol HTTP or HTTPS

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.

like image 763
henrywright Avatar asked Sep 01 '25 18:09

henrywright


1 Answers

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]
like image 68
Mike Rockétt Avatar answered Sep 04 '25 08:09

Mike Rockétt