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 parameterSCRIPT_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; } } }