redirect blocked ip to different url in nginx

Jhilke Dai asked:

In my Nginx config I have

location / {
allow 198.168.0.1;
deny all;
}

Now, I want to redirect all other IPs except the allowed one to google.com, how do I do that ?

I have tried something like

location / {
allow 198.168.0.1;
deny all;
rewrite ^ http://google.com/;
}

but this redirects directly to google.com for all IP. I want only 198.168.0.1 to access the page, others would be redirected.

My answer:


Use the error_page directive for this.

location / {
    allow 198.168.0.1;
    deny all;
    error_page 403 http://www.google.com/;
}

Since the deny all will serve a 403 error, we override the 403 handling by sending a redirect to http://www.google.com/.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.