Handy config snippet: Redirect to canonical server name

Igor Sysoev is at rambler-co.ru
Fri Aug 7 12:18:33 MSD 2009


On Sat, Aug 01, 2009 at 04:26:03AM +1000, Jeff Waugh wrote:

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

This snippet is probably handy, however, it will run useless regex for every
request for www.example.com. Using separate example.com server is better
for perfomance reason.


-- 
Igor Sysoev
http://sysoev.ru/en/





More information about the nginx mailing list