It is good for SEO to stick to either www or non-www.

Normally you can force this with Apache using the virtual host configuration or a .htaccess file, for example:

Force www using .htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Force www using NginX configration:

server {
    listen 80;
    server_name domain.com;
    return 301 $scheme://www.example.com$request_uri;
}

server {
    listen 80;
    server_name www.example.com;
}

If you are unable to edit your .htaccess file on Apache or your NginX configuration, or indeed any other webserver running PHP, you can use the following to permanently redirect to www or non-www in your URL.

Force www or non-www

The next two examples show how to force www or non-www regardless of whether you are serving over HTTP or HTTPS / SSL.

Force www

$https_set = $_SERVER['HTTPS'] ?? false;
$protocol = ($https_set === 'on') ? "https://" : "http://";
if (strncmp($_SERVER['HTTP_HOST'], 'www.', 4) === 0) {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $protocol . 'www.' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}

Force non-www

$https_set = $_SERVER['HTTPS'] ?? false;
$protocol = ($https_set === 'on') ? "https://" : "http://";
if (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}

Force www or non-www and force https

The last two examples show how to force www or non-www and force HTTPS / SSL.

Force www and https

if (strncmp($_SERVER['HTTP_HOST'], 'www.', 4) === 0) {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: 'https://www.' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}

Force non-www and https

if (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}