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).


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


/etc/nginx/sites-enabled/example.com:
    server {
        listen  10.0.0.1:80;
        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...

Enjoy!

- Jeff

-- 
linux.conf.au 2010: Wellington, NZ                http://www.lca2010.org.nz/
 
             http://www.xach.com/debian-users-are-beatniks.html





More information about the nginx mailing list