Setting a header inside an if block

I currently have:

server{

if ($remote_user = “”) {
return 401;
}

}

But what I really want is:

server{

if ($remote_user = “”) {
add_header WWW-Authenticate ‘Basic realm=“mydomainhere.com”’;
return 401;
}

}

But nginx won’t allow me to use the add_header directive inside an if
block.
How can I achieve this?

Posted at Nginx Forum:

On 05.02.2014 19:31, justink101 wrote:

But what I really want is:
But nginx won’t allow me to use the add_header directive inside an if block.
How can I achieve this?

via Module ngx_http_auth_request_module


Best regards,
Gena

I don’t have the auth_request module? All I need to do, is set the
WWW-Authenticate header.

Posted at Nginx Forum:

On Wed, Feb 05, 2014 at 05:12:55PM -0500, justink101 wrote:

I don’t have the auth_request module? All I need to do, is set the
WWW-Authenticate header.

So you only want to ensure that the basic authentication
was attempted, but don’t want to check the credentials on
the nginx side? Here’s how:

http {
map $remote_user $realm {
‘’ mydomainhere.com;
default off;
}

server {

auth_basic $realm;
auth_basic_user_file /dev/null;
}
}

It means that HTTTP basic authentication by nginx will be
disabled (“off”) if $remote_user is not empty, and enabled
(and return 401 with an appropriate header) otherwise.

Thanks that worked perfectly, though I must admit, a bit of a
round-a-bout
solution.

Posted at Nginx Forum: