snipt

Ctrl+h for KB shortcuts
Notice: Snipt is moving away from free accounts on May 1st, 2014. Read more about the transition here.
#22289

Nginx configuration file

www-to-nonwww and reverse

# www to non-www
server{
  listen 81;
  server_name  www.domain.com;
  rewrite ^(.*) http://domain.com$1 permanent;
}

# non-www to www
server {
  if ($host ~* ^([a-z0-9\-]+\.(com|net|org))$) {
    set $host_with_www www.$1;
    rewrite ^(.*)$ http://$host_with_www$1 permanent;
  }
}
https://snipt.net/embed/e05b910bf3d23a2b03f4bb10a4370de5/
https://snipt.net/raw/e05b910bf3d23a2b03f4bb10a4370de5/
e05b910bf3d23a2b03f4bb10a4370de5
nginx
Nginx configuration file
14
2014-04-24T15:47:15
True
False
/api/public/snipt/22289/
www-to-nonwww-and-reverse
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1"> 1</a> <a href="#L-2"> 2</a> <a href="#L-3"> 3</a> <a href="#L-4"> 4</a> <a href="#L-5"> 5</a> <a href="#L-6"> 6</a> <a href="#L-7"> 7</a> <a href="#L-8"> 8</a> <a href="#L-9"> 9</a> <a href="#L-10">10</a> <a href="#L-11">11</a> <a href="#L-12">12</a> <a href="#L-13">13</a> <a href="#L-14">14</a></pre></div></td><td class="code"><div class="highlight"><pre><span id="L-1"><a name="L-1"></a><span class="c1"># www to non-www</span> </span><span id="L-2"><a name="L-2"></a><span class="k">server{</span> </span><span id="L-3"><a name="L-3"></a> <span class="s">listen</span> <span class="mi">81</span><span class="p">;</span> </span><span id="L-4"><a name="L-4"></a> <span class="k">server_name</span> <span class="s">www.domain.com</span><span class="p">;</span> </span><span id="L-5"><a name="L-5"></a> <span class="k">rewrite</span> <span class="s">^(.*)</span> <span class="s">http://domain.com</span><span class="nv">$1</span> <span class="s">permanent</span><span class="p">;</span> </span><span id="L-6"><a name="L-6"></a><span class="k">}</span> </span><span id="L-7"><a name="L-7"></a> </span><span id="L-8"><a name="L-8"></a><span class="c1"># non-www to www</span> </span><span id="L-9"><a name="L-9"></a><span class="s">server</span> <span class="p">{</span> </span><span id="L-10"><a name="L-10"></a> <span class="kn">if</span> <span class="s">(</span><span class="nv">$host</span> <span class="p">~</span><span class="sr">*</span> <span class="s">^([a-z0-9\-]+\.(com|net|org))</span>$<span class="s">)</span> <span class="p">{</span> </span><span id="L-11"><a name="L-11"></a> <span class="kn">set</span> <span class="nv">$host_with_www</span> <span class="s">www.</span><span class="nv">$1</span><span class="p">;</span> </span><span id="L-12"><a name="L-12"></a> <span class="kn">rewrite</span> <span class="s">^(.*)</span>$ <span class="s">http://</span><span class="nv">$host_with_www$1</span> <span class="s">permanent</span><span class="p">;</span> </span><span id="L-13"><a name="L-13"></a> <span class="p">}</span> </span><span id="L-14"><a name="L-14"></a><span class="p">}</span> </span></pre></div> </td></tr></table>
nginx