The right way is to define a separated server for the naked domain and redirect it.
server {
listen 80;
server_name example.org;
return 301 $scheme://www.example.org$request_uri;
}
server {
listen 80;
server_name www.example.org;
...
}
Note that this also works with HTTPS site.
You will need 2 server blocks for this:
server {
listen 80;
server_name example.org;
}
server {
listen 80;
server_name www.example.org;
return 301 $scheme://example.org$request_uri;
}
server {
listen 80;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
# let the browsers know that we only accept HTTPS
add_header Strict-Transport-Security max-age=2592000;
...
}