Nginx-2.初学者使用

原文

Nginx有一个master进程和几个worker进程。master进程用来读取和评估配置文件,以及维护worker进程。worker进程用来处理实际的请求。Nginx使用事件模型和基于操作系统的逻辑来实现高效的worker处理进程。worker进程的数量可以定义到配置文件中,或者根据cpu核心数来自动调节。

默认配置文件nginx.conf,默认地址nginx/conf

启动,停止,重新加载配置文件

语法

nginx -s signal

signal可以是以下几个:

  • stop 快速停止
  • quit 优雅停止
  • reload 重新加载配置文件
  • reopen 重新打开配置文件

demo:

nginx -s quit #优雅的停止。和启动的用户必须是同一个。
nginx -s reload #改了配置文件要重洗加载生效。

nginx收到reload信号之后,master进程会检查配置文件,如果没有过,回滚配置,继续使用旧的配置文件。如果过了,会先生成一个新的worker进程,然后给老的worker进程发送信号。老的worker进程收到消息会停止接收新的连接,但是会执行完已经存在的连接,最后退出。

Unix系统的kill命令也可以用来发送signal给nginx。假设nginx的master进程id是1628,使用下面格式

kill -QUIT 1628

ps用来看所有的nginx进程

ps -ax | grep nginx

配置文件的结构

nginx的模块(功能)通过配置文件的指令来控制。指令分为简单指令块指令简单指令由指令名和参数构成,中间用空格分隔,以分号结尾。块指令由指令名后跟{}构成。

如果一个指令块可以包含其他指令,这个就是一个Context,比如 eventshttpserverlocation

配置文件最外层的指令叫main context。比如eventshttp

# 表示注释。

简单来说,一个配置文件要一个http,包含一个server,server包含一个location就可以了。

为静态内容提供服务

通过server块指令里面listenserver_name指令来判断具体的server。然后再根据里面的location指令块的参数来判断。

先定义一个http指令块。

http{
  server{
    listen 8080;#可以写127.0.0.1:8080等
    server_name localhost;#域名
  }
}

server里面放location

location / {
  root /data/www;
}

请求匹配location的/地址,把后面的内容加到root指令参数"/data/www"后面,可以指向到物理地址。如果有多个匹配,nginx会选最长的。

比如再加一个

location /images/ {
  root /data;
}

那么images的匹配会到后面这个。

改完之后reload生效配置文件。

nginx -s reload

设置一个简单的代理服务器

设置两个nginx实例。

第一个

server {
  listen 8080;
  root /data/up1;
  
  location / {
    
  }
}

所有8080的请求都会到/data/up1下面。

第二个

server {
  location / {
    proxy_pass http://localhost:8080;
  }
  location ~ \.(gif|jpg|png)& {
    root /data/images;
  }
}

通过正则(正则表达式必须以~和空格开头)匹配gif等图片文件,请求映射到/data/images目录下,其他的通过proxy_pass指令代理到localhost:8080下面。

设置一个FastCGI代理

CGI(Common Gateway Interface) is an interface specification for web servers to execute programs that execute like console applications (also called command-line interface programs) running on a server that generates web pages dynamically.

nginx 可以把请求路由转发到一些比如php写的框架服务上。基本的用法是使用fastcgi_pass指令替换proxy_pass指令。然后用fastcgi_param来设置需要的转发的参数。

举个例子:

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;
  }
}
posted @ 2020-02-24 08:39  Sheldon_Lou  阅读(167)  评论(0编辑  收藏  举报