Linux – Can’t get virtual hosts (server blocks) on Nginx to work

configurationlinuxnginx

I'm just started with Nginx am trying to use virtual hosts, but can't wrap my head around what's wrong with my config…

Here are the sontents of the sites-enabled folder:

root@cavalier:/etc/nginx/sites-enabled# ls -hal
total 12K
drwxrwxr-x 2 root vnc  4.0K Jul 28 18:06 .
drwxr-xr-x 5 root root 4.0K Jul  1 16:58 ..
-rw-r--r-- 1 root root  360 Jul 28 18:07 default
lrwxrwxrwx 1 root root   31 Jul 28 18:01 example1.com -> ../sites-available/example1.com
lrwxrwxrwx 1 root root   33 Jul 28 17:57 example2.com -> ../sites-available/example2.com

The contents of the default server block:

root@cavalier:/etc/nginx/sites-enabled# cat default
server {
listen 80 default_server;

root /www/example.com;
index index.html index.php;

location / {
try_files $uri $uri/ =404;
}

location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}

The example 1 server block:

root@cavalier:/etc/nginx/sites-enabled# cat example1.com
server {
listen example1.com:80;
server_name www.example1.com example1.com;

root /www/example1.com;
index index.html index.php;

location / {
try_files $uri $uri/ =404;
}

location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}

The example2 server block:

root@cavalier:/etc/nginx/sites-enabled# cat example2.com
server {
server_name example2.com;

root /www/example2.com;
index index.php;

location / {
try_files $uri $uri/ =404;
}

location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}

For some reason nginx only serves files from example1.com, for all domains. It even disregards the default server config and goes straight to example1.

Pardon me, I'm new to nginx, and have mostly been using Apache. I'm guessing this should be relatively simple and I'm just missing something… I've spend hours trying to figure it out though, and any help would be appreciated.

Best Answer

Server1 has most specific match to the request: IP:port, while two others match only port. So nginx choose server1 for all requests that comes to this IP:port pair