Nginx – setup nginx with IP as server name

nginx

How to setup nginx with IP address as server name?

server {
    listen  80;
    server_name  xx.xx.xx.xx;

    location /test {
        root  /var/www/test;
    }

    location ~ \.php$ {
        include  /var/ini/nginx/fastcgi.conf;
        fastcgi_pass  php;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME /var/www/test$fastcgi_script_name;
    }
}

So I want to access the server like this

http://xx.xx.xx.xx/test/ => index.php
http://xx.xx.xx.xx/test/foo.php => foo.php

Best Answer

You can just put the IP address as the server name:

server {
    listen 80;
    server_name 192.168.1.21;
    ...
}

You may also want to change the configuration to only listen on the specified IP address:

server {
    listen 192.168.1.21:80;
    server_name 192.168.1.21;
    ...
}

The following is from the docs: http://nginx.org/en/docs/http/server_names.html

If someone makes a request using an IP address instead of a server name, the “Host” request header field will contain the IP address and the request can be handled using the IP address as the server name:

server {
    listen       80;
    server_name  example.org
                 www.example.org
                 ""
                 192.168.1.1
                 ;
    ...
}