Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have 2 sites-enabled, with server_name as follows:

server_name www.mysite.com mysite.com

and

server_name dev.mysite.com

Problem: When I access the website via its IP address, by looking at the access/error logs, it appears that nginx is serving off the root of dev.mysite.com.

How does nginx decide which to serve? Can we force it to serve off the root of www.mysite.com when the site is visited using its ip address?

conf

server {
    listen   80;
    server_name www.mysite.com mysite.com;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    root /var/www/mysite/public;

    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$args ;
    }
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_read_timeout 300;
    }

}
share|improve this question
add comment

2 Answers 2

up vote 5 down vote accepted

Briefly: you haven't told Nginx which server {...} to choose from - so it chose the first one.

Nginx passes requests to the default server. To do this, it matches the Host header against the server_name. If an IP address is used, the Host header will contain the IP address (which means it can be used to match against the server_name).

In the case where no server_name matches the Host header, nginx will choose the server in the following way:

  1. The server explicitly set as default.
    • This is done (in the case of port 80) with listen 80 default_server
  2. If there is no default_server, the first server listed in the configuration is used.
    • It is important to note that, when using wildcards, the order of file inclusion in nginx is indeterminate

To quote from the Nginx wiki:

If the directive has the default_server parameter, then the enclosing server {...} block will be the default server for the address:port pair. This is useful for name-based virtual hosting where you wish to specify the default server block for hostnames that do not match any server_name directives. If there are no directives with the default_server parameter, then the default server will be the first server block in which the address:port pair appears. The default_server parameter appeared in version 0.8.21 thus deprecating the parameter default.

Recommended reading:

share|improve this answer
add comment

root can also be defined under http scope before server. You can set your default root there.

html {
    root /default/root

    server {
        root /site/root
    }
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.