Nginx的各種配置

suliangyi2012發表於2014-05-28

1.服務配置

server {

listen 80 default_server;       //default_server:就是設定預設的請求首先分發到此服務上,一般如果沒有此命令,第一個server就會當做預設的服務

server_name example.org www.example.org;

}

server {

listen 80 ; 

server_name example.net www.example.net;

}

server {
    listen      80;
    server_name "";如果請求沒有HOST,返回444,
    return      444;
}
//以下是基於IP和基於name的虛擬服務配置
server {
    listen      192.168.1.1:80;
    server_name example.org www.example.org;
    ...
}
比較全的server
/*
nginx first searches for the most specific prefix location given by literal strings regardless of the listed order. In the configuration above the only prefix location is “/” and since it matches any request it will be used as a last resort. Then nginx checks locations given by regular expression in the order listed in the configuration file. The first matching expression stops the search and nginx will use this location. If no regular expression matches a request, then nginx uses the most specific prefix location found earlier.
*/
server {
    listen      80;
    server_name example.org www.example.org;
    root        /data/www;

    location / {
        index   index.html index.php;
    }

    location ~* \.(gif|jpg|png)$ {
        expires 30d;
    }
/*
The fastcgi_param directive sets the FastCGI parameter SCRIPT_FILENAME to “/data/www/index.php”, and the FastCGI server executes the file. The variable $document_root is equal to the value of the root directive and the variable $fastcgi_script_name is equal to the request URI, i.e. “/index.php”.
A request “/about.html” is matched by the prefix location “/” only, therefore, it is handled in this location. Using the directive “root /data/www” the request is mapped to the file /data/www/about.html, and the file is sent to the client.
Handling a request “/” is more complex. It is matched by the prefix location “/” only, therefore, it is handled by this location. Then the index directive tests for the existence of index files according to its parameters and the “root /data/www” directive. If the file /data/www/index.html does not exist, and the file /data/www/index.php exists, then the directive does an internal redirect to “/index.php”, and nginx searches the locations again as if the request had been sent by a client. As we saw before, the redirected request will eventually be handled by the FastCGI server.
*/
location ~ \.php$ { fastcgi_pass localhost:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }

     負載均衡
負載均衡的方法有三種:輪循,最小連線法,ip_hash法,權重法

http {
    upstream myapp1 {
        least_conn;//或者ip_hash,預設是輪循,可以不寫出來
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }
    }
}

相關文章