0

I want to force HTTPS throughout the site, which is already done no problem with the below:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NC,NE]

But I also want to make sure requests that go to the apex domain get redirected to www.example.com

I found this answer, but seems this would redirect subdomains to www as well? ...or maybe it won't as don't subdomains use their own .htaccess?

In addition to the above, I tried the below for the www. portion, but it doesn't seem to work?

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g|gif|bmp|png|ico|js|css|woff|ttf|eot|svg)|webp$ [NC]
RewriteRule ^ https://www.example.com/%{REQUEST_URI} [R=301,L,NC,NE]

I thought this would fail if it doesn't start with example.com and hence will leave ANY subdomain alone, including www?

But it doesn't seem to be triggering at all.

Noah
  • 859
  • 7
  • 17
Brett
  • 19,449
  • 54
  • 157
  • 290
  • Did you clear your browser caches? – Amit Verma Jan 12 '22 at 04:28
  • @AmitVerma Yes, I believe so. – Brett Jan 12 '22 at 15:48
  • Whilst the rules you've posted are not necessarily the most optimal, they should still "work". What other directives do you have in your `.htaccess` file? Please include your complete `.htaccess` file with these directives in place. To clarify, `example.com` does resolve to the same place as the www subdomain? – MrWhite Jan 17 '22 at 00:23

1 Answers1

1

This config should work for your needs:

RewriteEngine On

# When on the root domain (with HTTPs; on "www" or the root domain only):
#  Redirect to WWW Root
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} ^(?!www\.)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]

# When HTTP is off (on "www" or the root domain only)
#  Redirect to the HTTPs Version of the WWW root
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^(?:www\.|)(example\.com)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NC,NE]

You can also test your config using this website.

Noah
  • 859
  • 7
  • 17