redirecting non www to www.

Igor Sysoev is at rambler-co.ru
Mon Jan 15 08:28:03 MSK 2007


On Sun, 14 Jan 2007 ianevans at digitalhit.com wrote:

> Just trying to clean things up for Google's duplicate issues...this might
> be a basic example to toss in the rewrite module part of the wiki for
> people who suck at regex's like me. <g>
>
> So a) who would you redirect a example.com request to www.example.com and
> b) where would it go in the order of the locations:
>
> location / {
> ...
> }
>
> location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|js|mov)$ {
> ...
> }

You may set the "rewrite" at server level:

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

         if ($http_host ~* ^example.com$ {
             rewrite ^(.*) http://www.example.com$1 permanent;
         }

         location / {
             ...
         }

         location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|js|mov)$ {
             ...
         }

however, how it was already suggested it's better to separate servers:

     server {
         server_name  example.com;
         rewrite ^(.*) http://www.example.com$1 permanent;
     }

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

because

1) it's clearer
2) and the frequent requests to www.example.com would not run
    unnecessary "if" and regex.
3) nginx is optimized to run tens thousands of virtual host names.


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





More information about the nginx mailing list