Rewriting the domain part of Set-Cookie in a proxy_pass

agentzh agentzh at gmail.com
Wed Sep 14 08:49:43 UTC 2011


On Wed, Jun 8, 2011 at 9:16 PM, tobia <nginx-forum at nginx.us> wrote:
> Does nginx (or a module) provide functionality equivalent to httpd's
> ProxyPassReverseCookieDomain?
>
> Long explanation: I have a simple nginx reverse proxy
>
> server {
>  server_name external.domain.com;
>  location / {
>    proxy_pass http://backend.int/;
>  }
> }
>
> The problem is that Set-Cookie response headers contain
> ";Domain=backend.int", because the backend does not know it is being
> reverse proxied. Therefore the users' browsers dutifully reject such bad
> cookies.
>
> How can I rewrite the content of the Set-Cookie response headers,
> replacing ";Domain=backend.int" with ";Domain=external.domain.com"?
>

Now with the latest ngx_lua v0.3.1rc3, we can implement this with a
little inlined Lua in nginx.conf:

    server_name external.domain.com;

    location / {
        proxy_pass http://backend.int/;

        header_filter_by_lua '
            local cookies = ngx.header.set_cookie
            if not cookies then return end
            local newcookies = {}
            for i, val in ipairs(cookies) do
                local newval = string.gsub(val, "([dD]omain)=[%w_-\\\\.]+",
                          "%1=external.domain.com")
                table.insert(newcookies, newval)
            end
            ngx.header.set_cookie = newcookies
        ';
    }

We can surely make this more portable by avoiding hard-coding the
"external.domain.com" literal in our Lua code and reference
ngx.var.server_name (i.e., the nginx variable $server_name) instead ;)

See the ngx_lua documentation for more details:

    http://wiki.nginx.org/HttpLuaModule

The most relevant sections are

    http://wiki.nginx.org/HttpLuaModule#header_filter_by_lua

and

    http://wiki.nginx.org/HttpLuaModule#ngx.header.HEADER

Have fun!
-agentzh



More information about the nginx mailing list