'I fail at redirecting www to NON-WWW domain nginx

I try to redirect a www to a non-www site but I am not successful. I tried multiple suggestions from other people but I failed. I undid the changes which were suggested on other websites and here is my .CONF:

 server {
            root /var/www/html/DOMAIN.de;
            index index.php index.html index.htm;
            server_name DOMAIN.de www.DOMAIN.de;

            error_log /var/log/nginx/DOMAIN.de_error.log;
            access_log /var/log/nginx/DOMAIN_access.log;
            client_max_body_size 100M;

            location / {
                  try_files $uri $uri/ /index.php?$args;
            }




            location ~ \.php$ {
                  include snippets/fastcgi-php.conf;
                  fastcgi_pass unix:/run/php/php8.1-fpm.sock;
                  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            }

        listen [::]:443 ssl ipv6only=on; # managed by Certbot
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/DOMAIN.de/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/DOMAIN.de/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    }
    server {
        if ($host = DOMAIN.de) {
            return 301 https://$host$request_uri;
        }


            listen 80;
            listen [::]:80;


Solution 1:[1]

maybe you have to put it like this:

server {
       listen 80;
       server_name example.com;
       root /var/www/www.example.com/web;

       if ($http_host != "www.example.com") {
                 rewrite ^ http://example.com$request_uri permanent;
       }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tempo