Forcing https non-www for every variants on Ubuntu 18.10/Apache

Posted March 30, 2019 542 views
ApacheUbuntu 18.04

Trying to force https non www on all variations of the url:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]

This is the code that i’m using.

It works well for http w/o www but it doesn’t work on (https with www)

P.S: i have two DNS records type A on my domain pointing to the same ip: @, www and a letsencrypt ssl certificate.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer


I just came across this question. The following rule usually works for me:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]