Regular Expression global redirect

António P. P. Almeida appa at perusio.net
Sun Feb 26 04:41:08 UTC 2012


On 26 Fev 2012 04h59 CET, nginx-forum at nginx.us wrote:

> I'm using nginx as a reverse proxy for about 2000 websites. I'm
> trying to find a good way to redirect all www traffic to nonwww
> addresses. I don't want to have a separate entry for every
> domain...just a global redirect in the server block preferably. I
> found lots of examples to do this one domain at a time, but does
> anyone have any suggestions on how to do it for the whole server?
>
> I was thinking of extracting the domain something like this then
> using an if statement, but I understand that if's are not
> recommended:
>
> server_name ~^(\.)?(?<domain>.+)$;
>
> thanks,
> altimage
>
> here's my server block:
>
> server {
> 	listen 80;
> 	server_name	_;
>
> 	location / {
> 		proxy_pass  http://websites;
> 	}
> }
Try:

server {
    server_name ^~www\.(?<domain>.*)$;   
    return 301 http://$domain;
}

server {
    server_name ^~(?<domain_name>[^\.]*)\.(?<tld>[^\.]*)$;

    location / {
        proxy_pass http://$domain_name.$tld;
   }
}

--- appa



More information about the nginx mailing list