Regular Expression global redirect

António P. P. Almeida appa at
Sun Feb 26 14:39:38 UTC 2012

On 26 Fev 2012 07h19 CET, edho at wrote:

> 2012/2/26 António P. P. Almeida <appa at>:
>> server {
>>    server_name ^~www\.(?<domain>.*)$;
>>    return 301 http://$domain;
>> }
> Where can I read the documentation for this? It doesn't seem to be
> mentioned in docs and nginx wiki

AFAIK it's undocumented. You can use return for a lot of things. I
hardly ever use rewrite anymore. There are situations where it still
applies, but they're not the majority. 

IMHO using return is more Nginx like, while rewrite harks back to
Apache's mod_rewrite and its "reverse" logic.

Using return you can make a poorman's web service, for example:

location /ws-test {
    return 200 "{uri: $uri, 'service name': 'this is a service'}\n";

If you do a capture in the location you can use the captures in the
URI you give return as the second argument. The default status is
302. AFAIK it doesn't support named locations redirects. Hence the
usual idiom of returning an error status and then using error_page for
the redirect with a named location.

It was late and I forgot the $request_uri :( 

Also for old PCRE versions the ?<name> has to be replaced by ?P<name>. 

Both things that were already addressed in the thread.

--- appa

More information about the nginx mailing list