This is a simple rule for .htaccess to redirect all non www urls to www.
RewriteCond %{HTTP_HOST} !^www\\. [NC]
RewriteRule ^(.*)$ <http://www>.%{HTTP_HOST}/$1 [R=301,L]
Cloudflare
If you're using Cloudflare this can be achieved with a page rule.
For URL enter domain.tld/*
For settings choose "Forwarding URL" and pick 301
For the forwarding URL put https://www.domain.tld/$1