Handy config snippet: Redirect to canonical server name

Jeff Waugh jdub at bethesignal.org
Fri Jul 31 22:26:03 MSD 2009

Hi all,

Here's a handy config snippet to permanently redirect to a canonical server
name, generically (ie. without needing to repeat yourself in every config).

    if ( $host != $server_name ) {
        rewrite  ^(.*)$  $scheme://$server_name$1  permanent;

    server {
        server_name  www.example.com example.com;
        include  canonical_hostname;

Because the included block in canonical_hostname is totally generic, you can
include it in whichever server block you wish. It automagically chooses the
correct scheme, host (based on the first element of server_name) and path...


- Jeff

linux.conf.au 2010: Wellington, NZ                http://www.lca2010.org.nz/

More information about the nginx mailing list