nginx

nginx基础教程(配置文件结构介绍及简单例子)

模块和指令:
nginx 由模块组成,这些模块由配置文件中指定的指令控制,指令分为简单指令和块指令。
一个简单的指令由名称和参数组成,由空格分隔并以分号 ( ;) 结尾。
块指令与简单指令具有相同的结构,但它不是以分号结尾,而是以一组由大括号 ({}) 包围的附加指令。

基本块结构:

http {
    server {
    }
}

下面的location要放到server块里:

location / {
    root /data/www;
}

location可以有多个,如果有多个匹配location块,nginx 会选择具有最长前缀的块。上面的location块是个斜杠“/”,提供了最短的前缀,长度为 1,因此只有当所有其他location 块都无法提供匹配时,才会使用这个块。

好的,接下来,server块里再加一个location块,它将匹配以/images/ (location /也匹配此类请求,但前缀较短) 开头的请求。

location /images/ {
    root /data;
}

整合后的配置文件结构为:

server {
    location / {
        root /data/www;
    }

    location /images/ {
        root /data;
    }
}

以上这个配置文件可以完成以下的意思:
标准端口 80 上侦听,为了响应以 URI 开头的请求/images/,服务器将从/data/images目录找文件。例如,为了响应 http://localhost/images/example.png请求,nginx 会找/data/images/example.png文件。如果这样的文件不存在,nginx 将发送一个响应,指示 404 错误。
不以 URI 开头的请求/images/将被映射到/data/www目录。例如,为了响应 http://localhost/some/example.html请求,nginx 会发送/data/www/some/example.html文件。

nginx还可以作为代理使用,但是静态图片使用本地文件,例如:

server {
    location / {
        proxy_pass http://localhost:8080/;
    }

    location ~ \.(gif|jpg|png)$ {
        root /data/images;
    }
}

nginx还可以作为Fastcgi的代理,nginx 可用于将请求路由到 FastCGI 服务器,这些服务器运行使用各种框架和编程语言(如 PHP)构建的应用程序。使用 FastCGI 服务器的最基本的 nginx 配置包括使用 fastcgi_pass 指令而不是proxy_pass指令,以及使用fastcgi_param 指令来设置传递给 FastCGI 服务器的参数。假设 FastCGI 服务器可以在localhost:9000. 以上一节中的代理配置为基础,将proxy_pass指令 替换为指令,fastcgi_pass并将参数更改为 localhost:9000. 在PHP中,SCRIPT_FILENAME参数用于确定脚本名称,QUERY_STRING 参数用于传递请求参数。

server {
    location / {
        fastcgi_pass  localhost:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param QUERY_STRING    $query_string;
    }

    location ~ \.(gif|jpg|png)$ {
        root /data/images;
    }
}

除了静态图像请求之外的所有请求路由到 localhost:9000通过 FastCGI 协议运行的代理服务器。

定义一个在没有给出host主机名的请求下,给出报错处理的例子:

server {
    listen      80;
    server_name "";
    return      444;
}

一个经典的php网站的配置文件例子:

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

    location ~ \.php$ {
        fastcgi_pass  localhost:9000;
        fastcgi_param SCRIPT_FILENAME
                      $document_root$fastcgi_script_name;
        include       fastcgi_params;
    }
}