Rewrite cond for domain and www.domain letsencrypt

I have this virtualhost in /etc/apache2/sites-available/cv.conf

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com

    DocumentRoot /var/www/cv/web
    <Directory /var/www/cv/web>
        AllowOverride All
        Order Allow,Deny
        Allow from All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/cv_error.log
    CustomLog ${APACHE_LOG_DIR}/cv_access.log combined
RewriteEngine on
RewriteCond %{SERVER_NAME} =www.example.com [OR]
RewriteCond %{SERVER_NAME} =example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

The lines Rewrite* have been added by letsencrypt and I checked on google, it seems to be the good way to do it. But when I go to domain.com it doesn't redirect me to https://example.com (it loads the 000-default.conf). Nevertheless it is redirecting me to https://www.example.com when I go on www.example.com

Do you have any idea? I don't know how to debug this. The logs are confirming what I am saying, the cv_access.log does not print any request when I go on domain.com.


Let's take a look at this line:

RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

Here, the %{SERVER_NAME} variable depends on the UseCanonicalName, by default set Off. Therefore, the variable has the content of Host: header, not the one specified in ServerName.

With UseCanonicalName On Apache httpd will use the hostname and port specified in the ServerName directive to construct the canonical name for the server.

With UseCanonicalName Off Apache httpd will form self-referential URLs using the hostname and port supplied by the client if any are supplied (otherwise it will use the canonical name, as defined above).

If you prefer to keep using mod_rewrite for this redirection, you have two options:

  1. Set UseCanonicalName On.
  2. Use the desired hostname directly in your rule, e.g.

    RewriteRule ^ https://example.com%{REQUEST_URI} [END,NE,R=permanent]
    

However, you are over-complicating things, as you could do the same without mod_rewrite:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com

    Redirect / https://example.com/
</VirtualHost>

Here, the the Redirect Directive comes from mod_alias, and you don't need DocumentRoot etc.