How i can set for a visitor host to use a specific root path in nginx?
Visitor with IP 1.1.1.1 will use
root /srv/web1
all other Visitors will use
root /srv/web2
Server Fault is a question and answer site for system and network administrators. It only takes a minute to sign up.
Sign up to join this communityHow i can set for a visitor host to use a specific root path in nginx?
Visitor with IP 1.1.1.1 will use
root /srv/web1
all other Visitors will use
root /srv/web2
While this question is easily answered by simply doing a bit of research and reading the documentation (preferably starting from the Beginner's Guide and then How nginx processes a request), I will answer it anyway.
I assume you have a server with more than one network interface and IP address, where the 1.1.1.1 address is assigned to one interface and other addresses to their respective interfaces.
Nginx is very flexible in this regard, in fact, there always is a server
block that is used as default when nginx can't match any other server block by server_name
: that is either the first server
block of the file or the one which specifies default_server
in its listen
directive. And remember that you can specify an IP in the listen
directive.
That means, in your case:
server {
listen 80 default_server;
root /srv/web2;
[...]
}
server {
listen 1.1.1.1:80;
root /srv/web1;
[...]
}
As you can see in the example above, the first server
block listens on all interfaces on port 80, while the second block listens only on the 1.1.1.1 interface, on port 80. Therefore, anyone visiting your site through the 1.1.1.1 network interface will receive files from /srv/web1, independently from the Host field in the HTTP request (that is, the domain name written in the URL bar).
Another similar behavior can be obtained by putting the IP address in the server_name
directive, like so:
server {
listen 80;
server_name 1.1.1.1;
[...]
}
* Note that this last server
block only catches requests to the literal IP address and not to domain names.
I hope this answers your question, but next time please put additional information about your current setup and please do some research.
To obtain the described behavior you can use the geo module as explained in this question:
geo $client {
default web2;
1.1.1.1 web1;
}
server {
[...]
root /srv/$client;
[...]
}
This config uses the geo module to set a variable ($client
) based on the client's IP address. That variable gets set to either the default web2 or the specific web1 and then is substituted in the root
directive.
Note that the geo
directive must be inside the http
block and not server
blocks; the snippet above should work as-is, but I don't guarantee anything since I did not test it.
if($remote_addr...)
, it doesn't work because you cannot put a root
directive inside an if
block. Read If Is Evil.