Regular Expression global redirect

António P. P. Almeida appa at perusio.net
Mon Feb 27 00:21:26 UTC 2012


On 27 Fev 2012 00h39 CET, nginx-forum at nginx.us wrote:

> I still cant seem to get this working. I upgraded my PCRE libraries
> and recompiled/reinstalled a fresh nginx 1.0.12
>
> # pcrecheck
> PCRE version 8.21 2011-12-12
>
> Here is my server sections. Notice I have 2 server sections...the
> 1st section catches the WWW site and redirects it to the 2nd,
> non-www...right? I'm still getting: nginx: [emerg] unknown "domain"
> variable
>
> server {
> listen 80;
> server_name ^~www\.(?<domain>.*)$;
> return 301 http://$domain;
> }
>
> server {
> listen 80;
> server_name ^~(?<domain_name>[^\.]*)\.(?<tld>[^\.]*)$;
> location / {
> proxy_pass http://websites;
> }
> }
>
> When I try it with the P, everything (www and nonwww) get a white
> 301 nginx page: server { listen 80; server_name
> ^~www\.(?P<domain>.*)$; return 301 $scheme://$domain$request_uri;; }
>
> server {
> listen 80;
> server_name _;
> location / {
> proxy_pass http://websites;
> }
> }
>
> I tried making server_name in the 2nd block:
> server_name ^~(?P<domain_name>[^\.]*)\.(?<tld>[^\.]*)$;
>
> but I get this:
> nginx: [emerg] invalid server name or wildcard
> "^~(?p<domain_name>[^\.]*)\.(?<tld>[^\.]*)$" on 0.0.0.0:80
> (fyi, the error has a lowercase p, server_name has it capitalized)
>
> Is there some other dependency I'm missing or am I just mangling the
> syntax?

Ok. It seems that your PCRE library has problems with the non P syntax
for named captures. So you cannot mix both.

server {
    listen 80;
    server_name ^~www\.(?P<domain>.*)$;
    return 301 $scheme://$domain$request_uri;
}

server {
    listen 80;
    server_name ^~(?P<domain_name>[^\.]*)\.(?P<tld>[^\.]*)$;
    location / {
        proxy_pass http://$domain_name.$tld;
    }
}

This should work [1]. 

--- appa

[1]  http://nginx.org/en/docs/http/server_names.html



More information about the nginx mailing list