wildcard to rewritre multi domains to www

Marcus Clyne maccaday at gmail.com
Sun Sep 6 23:23:50 MSD 2009


Hi,

Cliff Wells wrote:
> On Sat, 2009-09-05 at 23:53 +0300, Marcus Clyne wrote:
>   
>> Hi,
>>
>> Cliff Wells wrote:
>>     
>>> Try this:
>>>
>>> server {
>>>     server_name ~(^.+\..+$);
>>>     set         $name $1;
>>>     rewrite     ^ http://www.$name$request_uri? permanent;
>>> }
>>>
>>>   
>>>       
>> That will cause problems if the domain begins with www.  If you want to 
>> capture both www.domain.tld and domain.tld and rewrite to include the 
>> www., you could use
>>     
>
> That's odd, as I tested it and it worked fine ;-)   It specifically does
> not match domains starting with any subdomain, 
I think if you look at your regex again, you'll see that it's not that 
it doesn't match any domains with sub domains, it matches any domains 
with a dot somewhere in the middle.  The \. guarantees that there's a 
dot, but the other characters can be anything.
> it leaves that to another
> server section.   Here's the complete test I used:
>
>     server {
>         server_name ~^(.+\..+)$;
>         set         $name $1;
>         rewrite     ^ http://www.$name$request_uri? permanent;
>     }
>
>     server {
>         server_name www.test1.com;
>         root /var/www;
>         autoindex on;
>     }
>   
That will work because the second server will capture the www.test1.com, 
and the first will capture test1.com.  The second domain is matched 
before the first because it's an exact match.

However, if you just have the first pattern, then you'll get the rewrite 
as http://www.www.test.com$request_uri.  If you want to define the 
sub-domains separately, then of course that's fine, but you have to 
remember that there might be some domains with a single tld (e.g. 
test.com) and others with a country code too (e.g. test.co.uk).  If 
you're going to have a catch-all, then it's easier to stick to one regex 
IMHO.

Of course though, (as Igor mentioned) it's more efficient to define all 
the domains that you know the names of in the conf file itself.

Cheers,

Marcus.





More information about the nginx mailing list