title: Redirect nginx config server_name to custom 404 error page
body: <p>I'm new to nginx configs and have spent a lot of time googling so far. I'm trying to create a very basic nginx config file to be used in a "redirect" server. </p>
  
  <p>Users will be required to point naked domains (example.com) by A-record to my redirect server IP address, and the 'www' record by CNAME to another server.</p>
  
  <p>The purpose of the redirect server is to then perform a 301 redirect any/wildcard naked domains back to to the 'www' version of the domain so it can be properly handled by my other server. </p>
  
  <p>But I also want to catch any misconfigured 'www' domains that are pointing to my server IP by A-record, and simply direct them to a custom error page on the redirect server with further instructions on how to set up their account correctly for my service.</p>
  
  <p>Here's what I have. <strong>It works</strong>, but since I am new to writing configs I was wondering if there is a better way to handle the redirect to the custom error page in the first server block. TIA!</p>
  
  <pre><code>#redirect to error page if begins with 'www.'
  
  server {
      listen 80;
      server_name ~^www.; #only matches if starts with 'www.'. Is this good enough?
      rewrite ^(.*)$ /404.html; #is this the correct way to direct to a custom error page?
  
      error_page 404 /404.html;
  
      location  = /404.html {
          root /usr/share/nginx/html;
         }
      }
  
  #no match, so redirect to www.example.com
  
  server {
      listen 80 default_server;
      rewrite ^(.*)$ $scheme://www.$host$1 permanent;
  }
  </code></pre>