title: WWW to non-WWW Redirect with PHP
body: <p>I want to redirect all www.domain.com requests to domain.com with PHP, basically:</p>
  
  <pre><code>if (substr($_SERVER['SERVER_NAME'], 0, 4) === 'www.')
  {
      header('Location: http://' . substr($_SERVER['SERVER_NAME'], 4)); exit();
  }
  </code></pre>
  
  <p>However I do want to maintain the requested URL like in SO, for e.g.:</p>
  
  <pre><code>http://www.stackoverflow.com/questions/tagged/php?foo=bar
  </code></pre>
  
  <p>Should redirect to:</p>
  
  <pre><code>http://stackoverflow.com/questions/tagged/php?foo=bar
  </code></pre>
  
  <p>I don't want to rely on <code>.htaccess</code> solutions, and I'm unsure which <code>$_SERVER</code> vars I'd have to use to make this happen. Also, preserving the HTTPS protocol would be a plus.</p>
  
  <p>How should I do this?</p>