Search code examples
apacheapache2lets-encryptcertbot

non www to www apache2 Letscrypt certbot


I want to redirect my non-www to www . SSL working fine and both url working fine with ssl. https://example.com https://www.example.com both working but I want to redirect https://example.com to https://www.example.com

I am working with lamp-server in AWS ec2 and using certbot for ssl.

My apache config.

<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias example.com
    ServerAdmin [email protected]
    DocumentRoot /var/www/html

    <Directory /var/www/html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <IfModule mod_dir.c>
        DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
    </IfModule>
RewriteEngine on
RewriteCond %{SERVER_NAME} =example.com [OR]
RewriteCond %{SERVER_NAME} =www.example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

I tried many online tutorials but nothing helped, Thanks in advance for any help or support.


Solution

  • Try (note: Apache may throw errors if the comments starting with # are not removed):

    # turns on the rewrite engine
    RewriteEngine On
    # checks if domain is not www.example.com
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    # redirects to www.example.com
    RewriteRule ^ https://www\.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    # the above is enough for 443 VirtualHost
    
    # checks if https is not on
    RewriteCond %{HTTPS} !on
    # redirects to https on the same domain
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 
    

    So, your full configuration:

    <VirtualHost *:80>
        ServerName www.example.com
        ServerAlias example.com
        ServerAdmin [email protected]
        DocumentRoot /var/www/html
    
        <Directory /var/www/html/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
        </Directory>
    
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    
        <IfModule mod_dir.c>
            DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
        </IfModule>
        RewriteEngine On
        RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
        RewriteRule ^ https://www\.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
        RewriteCond %{HTTPS} !on
        RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    </VirtualHost>
    

    Add the following to the <VirtualHost *:443> configuration:

        RewriteEngine On
        RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
        RewriteRule ^ https://www\.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]