Ubuntu/Debian nginx 简介

Linux运营维护(简称运维)

这里是简单的使用介绍:

参考:http://einverne.github.io/post/2017/06/ubuntu-debian-install-nginx.html  (安装和简介)

Nginx 配置参考文:  http://einverne.github.io/post/2017/10/nginx-conf.html

《Nginx》教程:https://www.oschina.net/translate/nginx-tutorial-basics-concepts?cmp

 


 

Nginx 是非常流行的 HTTP/HTTPS 服务器软件,它也可以作为反向代理服务器,邮件代理服务器,可以用于负载均衡,缓存等等。

基本的Nginx 由 master 进程和 worker 进程组成, master 读取配置文件,并维护 worker 进程,而 worker 会对请求进行处理。

 

Configuration File’s Structure

Directive指令分为单纯指令simple和block。

simple directive,包含名称和参数名,以分号结束,比如

gzip on;

block通常声明一个作用域,比如 server 块

server {
    listen 80;
}

如果block内有其他指令,则称为a context(上下文),如 events, http, server, location.

 

在配置文件中,放在任何contexts外面的指令directive被看成是位于main context内。

event, http等指令directive, 位于main context旁, server 可以在 http内, location 可以在 server内

 

Serving Static Content 服务分发静态内容

一个重要的web server task是serving out files.(分发文件,如图片或静态HTML pages).

比如根据请求request,文件从不同的本地目录/data/www, /data/images被分发served。这需要编辑配置文件并在http block内建立一个server block和2个location blocks.

 

Setting Up a Simple Proxy Server

nginx最频繁的用途之一是建立一个代理服务器proxy server, 意味着a server接受请求,传递 请求到代理服务器,再从代理服务器取回响应,并发送到客户端。

首先电影代理服务器,添加一个server block到nginx's的配置文件:

server {
    listen 8080;
    root /data/up1;

    location / {
    }
}

 

这是一个简单的服务器,它监听端口8080(previously, the listen directive has not been specified since the standard port 80 was use),并在本地的文件系统上,遍历所有请求到/data/up1目录。

创建这个目录并把index.html文件放入。

注意:root指令被放在server 上下文中。 Such root directive is used when the location block selected for serving a request does not include own root directive.

 

然后,第一个location block,把proxy_pass指令和协议htttp,名字localhost,代理服务端口8080放入参数中。

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

    location /images/ {
        root /data;
    }
}

 

修改第2个location block, 它会遍历请求(在/data/images目录内,找匹配请求的images)

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

 

参数 \.(gif|jpg|png)$ 是一个正则表达式,匹配所有以.gif | .jpg | .png结尾的image。

正则表达式前面加 ~, 代表这是一个正则表达式。

 

当nginx选择一个location block来server a request, 它首先检查location指令的指定前缀prefixes,

然后检查正则表达式。如果有一个匹配存在,则nginx pick 这个location,否则它pick the one remembered earlier.

 

这个代理服务器的配置结果是:

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

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

 

这个服务server 会过滤结尾是.gif /.jpg/.png的请求,并在/data/images目录遍历这些请求(通过增加URI到root目录的参数), 然后传递所有其他的请求到上面配置的代理服务器。

最后还要发送reload 到nginx,来应用这个新的配置

 



 

 

《Nginx》教程:

  • 基础概念——你可以了解命令(directive)与环境(context)的区别、继承模式,以及 Nginx 选择服务器区块的顺序,还有安装位置。

  • 性能管理——提升速度的诀窍。我们将会讲解 gzip、缓存、缓冲区以及超时设置。

  • SSL 设置——讲解用 HTTPS 来提供内容的设置步骤。


 

1. 基础概念

service nginx status : 查看状态。

nginx {start|stop|restart|reload|force-reload|status|configtest|rotate|upgrade}

 

nginx 的配置文件,默认的位置包括:

  • /etc/nginx/nginx.conf,

  • /usr/local/etc/nginx/nginx.conf,或

  • /usr/local/nginx/conf/nginx.conf

 


 

指令类型

有三种类型的指令,每种都有自己的继承模型。

  • Normal:  每个上下文只有唯一值
  • Array:  同一个context可以有多个。
  • Action directive:改变事情。根据模块的需要,它继承的行为可能会有所不同。⬇️案例:
server {
  rewrite ^ /foobar;

  location /foobar {
    rewrite ^ /foo;
    rewrite ^ /bar;
  }
}

如果用户取地址/sample:

  1. server rewrite 指令被执行,取地址指向/foobar;
  2. 然后用location /footbar,进行匹配;
  3. location内的第一个rewrite执行,重写:从/foobar 到/foo;
  4. location内的第二个rewrite执行,重写: 从/foo到/bar;

 

 

Processing request

在 Nginx 内部,你可以指定多个虚拟服务器virtual servers,每个虚拟服务器用 server{} 上下文描述

server {
  listen      *:80 default_server;
  server_name netguru.co;

  return 200 "Hello from netguru.co";
}

server {
  listen      *:80;
  server_name foo.co;

  return 200 "Hello from foo.co";
}

这将告诉 Nginx 如何处理到来的请求。

  • 首先,nginx用listen指令来过滤一下,找对应的端口。
  • 然后,server_name指令的值,会检测请求中的Host头部信息(主机域名)
  • 最后,根据匹配结果,选择用哪个虚拟主机。(关于匹配有优先级设置,具体看教程)

 

server_name 指令

server_name指令接受多个值。它还处理通配符匹配和正则表达式。

关于匹配有优先级设置,具体看教程)

 

listen 指令

在很多情况下,能够找到 listen 指令,接受IP:端口值。

listen 81;           # by default all ips are used

listen [::]:80;      # IPv6 addresses


Minimal configuration

With all that knowledge - we should be able to create, and understand minimal configuration needed for running nginx.

# /etc/nginx/nginx.conf

events {}             # events context needs to be defined to consider config valid

http {
 server {
    listen 80;
    server_name  netguru.co  www.netguru.co  *.netguru.co;

    return 200 "Hello";
  }
}

 

root, location, 和 try_files 指令

 

root指令 

root 指令设置请求的根目录,允许 nginx 将传入请求映射到文件系统。

根据给定的请求,指定 nginx 服务器允许的内容。

#Rails app的root目录:
root /home/deploy/vue-todolist/current/public;

/current/public$ ls 404.html apple-touch-icon-precomposed.png favicon.ico system 422.html apple-touch-icon.png packs uploads 500.html assets robots.txt

 

 

location directive

sets configuration, depending on requested URI

location [modifier] path
#例子:
location /foo/ {
  # ...
}

 

如果没有指定修饰符,则路径被视为前缀,其后可以跟随任何东西。👆的例子匹配:

/foo, /fooos, /foo123, /foo/bar/index.html等。

另外一个context内可以有多个location指令。

修饰符:

=           - Exact match
^~          - Preferential match
~ && ~*     - Regex match
no modifier - Prefix match

 

(具体匹配优先级看教程)

 

try_files指令

尝试不同的路径,找到一个路径就返回。

try_files $uri index.html =404;

 

先找$uri(/foo.html),没有就找index.html, 还没有就返回404

注意⚠️:不要在server context中定义这个指令,以location中定义为准。


 

 

2 性能Performance

 

tcp_nodelaytcp_nopush 和 sendfile

(三个提速的算法,具体使用见教程)

 

How many processes should I have?

Worker processes

它定义了应该运行多少个workers。最安全的设置是通过传递 auto 选项来使用核心数量。

 worker_processes auto;

 

 

Worker connections

和worker_process直接绑定的是worker_connections.它指定一个woker process一次可以打开多少个连接。

    events {
      worker_connections 768;
    }

 

 

Open files limit

在基于 Unix 系统中的“一切都是文件”。这意味着文档、目录、管道甚至套接字都是文件。系统对一个进程可以打开多少文件有一个限制。要查看该限制:

ulimit -Sn

如果设置限制的话,需要是worker_connections的至少2倍。

worker_process auto;
worker_rlimit_nofile 2048; # Changes the limit on the maximum number of open files (RLIMIT_NOFILE) for worker processes.
worker_connections 1024;   # Sets the maximum number of simultaneous connections that can be opened by a worker process.

 

 


 

 

Gzip

Enabling gzip should significantly reduce the weight of your response, thus it will appear faster on the client side.

启用 gzip 可以显著降低响应的(报文)大小,因此,客户端(网页)会显得更快些。

 

Compression level

gzip_comp_level 5;  #(一共有9级。 压缩级别越大,文件就越小,但resources consumption会增加!)

一般使用3-5级。

gzip on;               # 使用 gzip
gzip_http_version 1.1; # turn on gzip for http 1.1 and above
gzip_disable "msie6";  # IE 6 had issues with gzip
gzip_comp_level 5;     # 压缩级别
gzip_min_length 100;   # minimal weight to gzip file
gzip_proxied any;      # enable gzip for proxied requests (e.g. CDN)来自代理服务器的请求的响应可以压缩
gzip_buffers 16 8k;    # compression buffers (if we exceed this value, disk will be used instead of RAM)
gzip_vary on;          # add header Vary Accept-Encoding (more on that in Caching section)

# define files which should be compressed
gzip_types text/plain;
gzip_types text/css;
gzip_types application/javascript;
gzip_types application/json;
gzip_types application/vnd.ms-fontobject;
gzip_types application/x-font-ttf;
gzip_types font/opentype;
gzip_types image/svg+xml;
gzip_types image/x-icon;

 

 


 

 

Caching

Caching is another thing, that can speed up requests nicely, for returning users.

Managing the cache can be controlled just by 2 headers:

  • 在 HTTP/1.1 中用 Cache-Control 管理缓存

  • Pragma 对于 HTTP/1.0 客户端的向后兼容性

缓存本身可以分为两类:公共缓存和私有缓存。公共缓存是被多个用户共同使用的。专用缓存专用于单个用户。我们可以很容易地区分,应该使用哪种缓存:

add_header Cache-Control public
add_header Pragma public;

 

For standard assets we would also like to keep them for 1 month:

标准资源一般保存它们1个月:

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
  expires 1M;
  add_header Cache-Control public;
  add_header Pragma public;
}

#Rails的教程:
  location ~ ^/assets/ {
    expires 1y;
    add_header Cache-Control public;
    add_header ETag "";
    break;
  }

 

 


 

超时timeout

client_body_timeout 和 client_header_timeout 定义了 nginx 在抛出 408(请求超时)错误之前应该等待客户端传输主体或头信息的时间。

 

# Configure timeouts
client_body_timeout   12;
client_header_timeout 12;
send_timeout          10;

Buffers

client_body_buffer_size

设置读取客户端请求正文的缓冲区大小。如果请求主体大于缓冲区,则整个主体或仅其部分被写入临时文件。对 client_body_buffer_size 而言,设置 16k 大小在大多数情况下是足够的。

 

client_max_body_size

设置客户端请求主体的最大允许范围,在请求头字段中指定“内容长度”。如果您希望允许用户上传文件,调整此配置以满足您的需要。

# 设定档案上传可以到100mb,默认只有1Mb超小气的,上传一张图片就爆了
client_max_body_size 100m;

client_body_buffer_size       16K;
client_header_buffer_size     1k;
large_client_header_buffers   2 1k;

 

 


 

 

Keep-Alive

HTTP 所依赖的 TCP 协议需要执行三次握手来启动连接。这意味着在服务器可发送数据(例如图像)之前,需要在客户机和服务器之间进行三次完整的往返。

如果你在短时间内发送多次请求,这可能会快速累积起来。

keep-alive 使用起来就方便了。在成功响应之后,它保持连接空闲给定的时间段(例如 10 秒)。如果在这段时间内有另一个请求,现有的连接将被重用,空闲时间将被刷新。

在客户端和 nginx 之间 keep-alive

keepalive_disable msie6;        # disable selected browsers.

# The number of requests a client can make over a single keepalive connection. The default is 100, but a much higher value can be especially useful for testing with a load‑generation tool, which generally sends a large number of requests from a single client.
keepalive_requests 100000;

# How long an idle keepalive connection remains open.
keepalive_timeout 60;

 

在 nginx 和上游服务器之间 keep-alive

upstream backend {
    # The number of idle keepalive connections to an upstream server that remain open for each worker process
    keepalive 16;
}

server {
  location /http/ {
    proxy_pass http://http_backend;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
  }
}

 

posted @ 2018-11-01 16:26  Mr-chen  阅读(682)  评论(0编辑  收藏  举报