Nginx的配置文件
我的演示环境是在mac上使用homebrew安装的nginx,它的配置文件为/usr/local/etc/nginx/nginx.conf。
其实所有的配置都可以写在这个文件中,但是当文件过大时难以维护,所以通常的做法是按照模块或域名将配置拆分。
在nginx.conf文件的统计目录创建两个目录:servers/和upstreams/。
servers/中保存nginx的server的配置;
upstreams/中保存nginx的upstream的配置。
在servers/下创建m.domain.conf文件,内容如下:
server {
    listen       80;
    server_name  m.domain.com;
    location / {
        proxy_pass http://mobile.path;
    }
    location ~* ^/path($|/) {
        proxy_pass http://mobile.path;
    }
    location ~* ^/path01($|/) {
        proxy_pass http://mobile.path01;
    }
    location ~* ^/path02($|/) {
        proxy_pass http://mobile.path02;
    }
}
这样配置的目的是希望根据访问者url的二级目录来执行如下的分流规则:
http://m.domain.com/    -->    http://mobile.path
http://m.domain.com/path    -->    http://mobile.path
http://m.domain.com/path01    -->    http://mobile.path01
http://m.domain.com/path02    -->    http://mobile.path02
在upstreams/下创建m.upstream.conf文件,内容如下:
upstream mobile.path{
    server 127.0.0.1:8080;
}
upstream mobile.path01{
    server 127.0.0.1:8081;
}
upstream mobile.path02{
    server 127.0.0.1:8082;
}
这里配置的是分流的规则对应的主机列表。
在nginx.conf中配置如下的内容来指定日志的格式、日志的目录,以及包含配置文件:
...
http {
    ...
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$upstream_addr"';
    access_log  /Users/john/logs/nginx/access.log  main;
    ...
    include servers/*.conf;
    include upstreams/*.conf;
}
...