valid_referers dynamic hostname

Maxim Dounin mdounin at
Mon May 20 13:19:05 UTC 2013


On Sat, May 18, 2013 at 01:31:50PM -0400, vlad031 at wrote:

> Sorry for posting here - don't know for sure if it's the right place.
> I have an issue:
> 1) I use nginx as reverse proxy, but I don't always know the domain name for
> which I'm serving, so my setup looks like this:
> server_name  _ $host;

The "$host" string here means exactly "$host".  There is no 
variable expansion for server_name (expect for a special name 
"$hostname", which isn't actually a variable but a special name).

Most likely requests are handled in the sever{} block in question 
as it's used as a default server.

> 2) I try to block invalid referers but when I try to add $host to
> valid_referers - it doesn't seem to work:
> valid_referers none blocked server_names $host ~\.google\. ~\.yahoo\.
> ~\.bing\. ~\.ask\. ~\.live\. ~\\. ;

The valid_referers directive doesn't support variables.

> How can I make this work?
> Also please note that I don't know regexp.

What you are trying to do, i.e. allow referers which match Host 
header in a request, currently can't be done using the referers 
module only.

With a litle help from the rewrite module it's possible though.  
Something like this should work:

    valid_referers none blocked server_names ~\.google\. ...;

    set $temp "$host:$http_referer";

    if ($temp ~* "^(.*):https?://\1") {
        set $invalid_referer "0";

    if ($invalid_referer) {
        return 403;

Maxim Dounin

More information about the nginx mailing list