Regex on Variable ($servername)

Francis Daly francis at daoine.org
Fri Nov 10 08:19:28 UTC 2017


On Sun, Oct 29, 2017 at 11:53:23AM +0100, basti wrote:

Hi there,

> In this example from nginx docs domain has "fullname".
> 
> server {
>     server_name ~^(www\.)?(*?<domain>*.+)$;
>     root /sites/*$domain*;
> }

When I use the config

server {
    server_name ~^(www\.)?(?<domain>.+)$;
    return 200 "domain is $domain\n";
}

I get the message

nginx: [emerg] pcre_compile() failed: unrecognized character
after (?< in "^(www\.)?(?<domain>.+)$" at "domain>.+)$" in
/usr/local/nginx/conf/nginx.conf

because my PCRE version does not recognise that syntax.

The page at http://nginx.org/en/docs/http/server_names.html does say:

"""
The PCRE library supports named captures using the following syntax:

?<name>	Perl 5.10 compatible syntax, supported since PCRE-7.0
?'name'	Perl 5.10 compatible syntax, supported since PCRE-7.0
?P<name>	Python compatible syntax, supported since PCRE-4.0
If nginx fails to start and displays the error message:
pcre_compile() failed: unrecognized character after (?< in ...
this means that the PCRE library is old and the syntax “?P<name>” should be tried instead.
"""

When I change the main line (by adding an extra P) to be

    server_name ~^(www\.)?(?P<domain>.+)$;

then it all seems to work for me:

$ curl -H Host:www.example.com http://localhost/
domain is example.com
$ curl -H Host:example.com http://localhost/
domain is example.com
$ curl -H Host:no.example.com http://localhost/
domain is no.example.com

> servername: www.example.com -> $domain should be example.com

It works for me. What output do you get instead of what you want to get?

	f
-- 
Francis Daly        francis at daoine.org


More information about the nginx mailing list