I had a bit of a hard time 301 redirecting the following in Apache so I just want to document the sample configurations here:

# Redirecting to Non-WWW HTTPS

You'll usually encounter this problem when migrating to HTTPS to make sure your SEO is still good after. If you don't do proper 301 redirection you'll can get tagged for duplicate content and/or old links to your site might not also work properly which can also be confusing for your site visitors.

example.conf:

<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
Redirect permanent / https://example.com/
</VirtualHost>


example-ssl.conf

<VirtualHost *:443>
ServerName www.example.com

# Assuming using Let's encrypt
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf

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

<VirtualHost *:443>
ServerName example.com
DocumentRoot /var/www/example
...
...
...
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>


# Redirecting to WWW HTTPS

example.conf:

<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
Redirect permanent / https://www.example.com/
</VirtualHost>


example-ssl.conf

<VirtualHost *:443>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example
...
...
...
SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>


# Testing

You can test if your site is redirecting properly in your browser's developer tool. In Chrome for example, do a Ctrl-Shift-I and go to the Network tab. Go to the URL you want to test for redirection and check in the Network tab if it did a 301 redirection (instead of 200 or 404).