Use Nginx to server different pages depending on IP address/subnet
For reasons to hideous to go into... I'm using Nginx as a webserver and would like it to serve one page for internal users (say on 10.0.0.0/16) and another page to external users on any other IP address.
For example:
"Internal" PC with an IP of 10.0.0.34 goes to company.com/page.html gets page internal.html
"External" PC with an IP of 8.8.8.8 goes to company.com/page.html gets page external.html
Make use of Nginx geo module. It lets you set variable's value based on a client IP address. geo
directive must be in http
section:
http {
geo $client {
default extra;
10.0.0.0/8 intra;
}
You can use it later in locations to lookup files
location / {
try_files $uri.$client $uri = 404;
}
Which means, Nginx will set $client
to either extra
or intra
based on a client's IP. Let's assume it's a Intranet client. If a client asks for page.html
, Nginx will search for file /your/root/page.html.intra
. If there is no such file, it will search for /your/root/page.html
. If it cannot find neither of these, Nginx returns 404 "Not Found" response. More on "try_files" in the documentation
By the way, index
directive supports variables as well. E.g.
index index.$client.html index.html;