您的位置:首页 > 运维架构 > Nginx

Nginx作为静态web服务器详解

2017-09-17 21:59 429 查看




Nginx可以作为静态web服务器
Nginx在实际运维中,用到最多的地方是反向代理服务器,或负载均衡服务器
回顾httpd的MPM
回顾http的请求方法
回顾http的响应状态码
回顾http与URL

(二)
回顾IO模型


同步I/O:需要考虑其他任务的完成情况,任务是以串行方式完成的
异步I/O:无需考虑其他任务的完成情况,任务是并发方式完成的
系统调用详解

    简单的理解:应用程序需要执行特权级指令,就需要向内核代码发起系统调用,请求内核的进程去完成特权的操作,比如write操作。当内核进程代理应用程序完成了特权操作之后,就执行的结果再返回给调用者。这就是一次完整的系统调用过程

站在应用程序的角度看待系统调用过程:
同步等待:监听调用点,死等。阻塞
缺陷:性能不高,单位时间内执行的任务有限

异步等待:不会死等,可以做其他的事情。非阻塞
缺陷:context switch 切换速率频繁,CPU使用率高

同步阻塞: (调用结果返回之前,调用者会被挂起,一直等待消息通知)
同步非阻塞:(调用结果返回之前,调用者可以继续后续的任务,当调用通知返回的时候,会立即响应)
异步阻塞:(在等待通知这段时间内,也就是通知发给调用者这段时间内,调用者不能够继续后续的任务)

异步非阻塞:(在等待通知这段时间内,也就是通知发给调用者这段时间内,调用者还能够继续后续的任务)

linux的I/O模型


同步阻塞
同步非阻塞
I/O multiplexing
Signal Driven IO
AIO

(三)
Nginx
(一)


官方技术文档网站:http://nginx.org
Nginx的特性

1:各功能基于模块化设计,扩展性好

2:支持平滑重启,实现应用不下线部署

3:在多并发请求模型下,内存消耗低

4:支持事件驱动模型和异步I/O

5:支持FastCGI协议将动态请求发往后端的动态web服务器,支持WSGI(Python)等协议

6:2017-04-12版本已经支持:多类型的SSL certificate、DSO机制

7:master/worker架构模型:一个master主进程,可以生产多个worker子进程
...

Nginx应用场景

1:静态web服务器

2:http协议的反向代理服务器

3:邮件协议的反向代理服务器

(三)
Nginx
安装和核心模块介绍


Nginx的安装方法

1:yum安装
默认是1.6版本,且在epel源中

2:源码包编译安装
源码下载:http://nginx.org/en/download.html,下载1.8稳定版本

3:RPM包安装
RPM包下载:http://nginx.org/packages/centos/7/x86_64/

编译时候公网提供编译选项

./configure \
--prefix=/usr/local
--sbin-path=/usr/sbin/nginx
--conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--pid-path=/var/run/nginx.pid
--lock-path=/var/run/nginx.lock
--http-client-body-temp-path=/var/cache/nginx/client_temp
--http-proxy-temp-path=/var/cache/nginx/proxy_temp
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
--http-scgi-temp-path=/var/cache/nginx/scgi_temp
--user=nginx
--group=nginx
--with-http_ssl_module
--with-http_realip_module
--with-http_addition_module
--with-http_sub_module
--with-http_dav_module
--with-http_flv_module
--with-http_mp4_module
--with-http_gunzip_module
--with-http_gzip_static_module
--with-http_random_index_module
--with-http_secure_link_module
--with-http_stub_status_module
--with-http_auth_request_module
--with-threads
--with-stream
--with-stream_ssl_module
--with-http_slice_module
--with-mail
--with-ma
193a0
il_ssl_module
--with-file-aio
--with-http_v2_module
--with-ipv6

常用的编译选项(先添加Nginx用户和Nginx组,且安装development
tools 和 server platform development pcre-devel openssl-devel zlib-devel)

./configure --prefix=/usr/local/nginx1.8 --conf-path=/etc/nginx/nginx.conf --user=nginx --group=nginx --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --with-http_ssl_module --with-http_gzip_static_module --with-debug --with-http_stub_status_module

编译安装完成后启动Nginx、已经Nginx的常用命令讲解
(1)(在启动之前,先将命令添加到环境变量里面,再做一个软连接)

ln -sv /usr/local/nginx1.8 /usr/local/nginx

vi /etc/profile.d/nginx.sh 添加
export PATH=/usr/local/nginx/sbin:$PATH
. /etc/profile.d/nginx.sh

(2)启动Nginx
nginx

(3)查看nginx客户端程序的帮助
nginx -h

编写Nginx的service脚本文件,让其开机自启
(1)vi /etc/rc.d/init.d/nginx  添加
#! /bin/bash
# chkconfig: - 85 15
PATH=/usr/local/nginx
DESC="nginx daemon"
NAME=nginx
DAEMON=$PATH/sbin/$NAME
CONFIGFILE=/etc/nginx/nginx.conf
PIDFILE=/var/run/nginx/nginx.pid
SCRIPTNAME=/etc/init.d/$NAME
set -e
[ -x "$DAEMON" ] || exit 0
do_start() {
$DAEMON -c $CONFIGFILE || echo -n "nginx already running"
}
do_stop() {
$DAEMON -s stop || echo -n "nginx not running"
}
do_reload() {
$DAEMON -s reload || echo -n "nginx can't reload"
}
case "$1" in
start)
echo -n "Starting $DESC: $NAME"
do_start
echo "."
;;
stop)
echo -n "Stopping $DESC: $NAME"
do_stop
echo "."
;;
reload|graceful)
echo -n "Reloading $DESC configuration..."
do_reload
echo "."
;;
restart)
echo -n "Restarting $DESC: $NAME"
do_stop
do_start
echo "."
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|reload|restart}" >&2
exit 3
;;
esac
exit 0

(2)chmod +x /etc/rc.d/init.d/nginx

(3)chkconfig --add nginx

(4)chkconfig --level 35 nginx on

(5)chkconfig --list

模块类型分类

1:核心模块(重点)

2:标准模块
标准http模块(重点)
可选的http模块(重点)

3:第三方组织提供的模块

Nginx的配置文件说明
(编译安装的时候,将配置文件路径设置为/etc/nginx/nginx.conf)

[root@7 ~]# ll /etc/nginx/
总用量 60
-rw-r--r-- 1 root root 1034 9月 12 02:00 fastcgi.conf
-rw-r--r-- 1 root root 1034 9月 12 02:00 fastcgi.conf.default
-rw-r--r-- 1 root root 964 9月 12 02:00 fastcgi_params
-rw-r--r-- 1 root root 964 9月 12 02:00 fastcgi_params.default
-rw-r--r-- 1 root root 2837 9月 12 02:00 koi-utf
-rw-r--r-- 1 root root 2223 9月 12 02:00 koi-win
-rw-r--r-- 1 root root 3957 9月 12 02:00 mime.types
-rw-r--r-- 1 root root 3957 9月 12 02:00 mime.types.default
-rw-r--r-- 1 root root 2672 9月 13 01:53 nginx.conf (主配置文件)
-rw-r--r-- 1 root root 2656 9月 12 02:00 nginx.conf.default
-rw-r--r-- 1 root root 596 9月 12 02:00 scgi_params
-rw-r--r-- 1 root root 596 9月 12 02:00 scgi_params.default
-rw-r--r-- 1 root root 623 9月 12 02:00 uwsgi_params
-rw-r--r-- 1 root root 623 9月 12 02:00 uwsgi_params.default
-rw-r--r-- 1 root root 3610 9月 12 02:00 win-utf

主配置文件说明
(先将注释部分去掉:sed
-ri ‘/^#|[[:space:]]+#/d’ /etc/nginx/nginx.conf)

(1)全局配置段
1:指明运行worker进程的用户和组
user nginx nginx;

2:指明pid文件路径
pid /var/run/nginx.pid;

3:指明worker进程所能够打开的最大文件数(可以省略)
worker_rlimit_nofile 1024

4:worker的进程数,应该为CPU的核心数或核心数减一,如果是双核CPU,可以给2
worker_processes 2;

5:将nginx的worker进程,绑定在不同的CPU上, 如果分别绑定在第一颗和第二颗核心上,可以使用ps axo command,pid,psr 命令查看CPU的绑定情况
worker_cpu_affinity 0001 0010;

6:指定进程的nice值,nice值越小优先级越高
worker_priority 0;

7:指定以何种方式启动Nginx,默认是以daemon的方式启动
daemon on

8:指定是否使用master/worker模型启动nginx进程,默认是
master_process on

9:指定错误日志文件路径、日志级别
error_log logs/error.log error;

(2)event配置段

1:指定单个worker进程打开的最大socket连接数,默认为512,但是必须小于worker进程所能够打开的最大文件数
worker_connections 512;

2:指明处理并发连接请求时,使用的网络I/O处理方式,无需管理,linux自行判断
use method;

3:指明worker进程是否支持轮询响响应的新请求
accept_mutex on;

4:指明锁文件路径
lock_file /var/lock/nginx.lock;

(3)http配置段
1:指明mime类型,用于数据传输
default_type text/plain;
或 default_type application/octet-stream;

2:指定是否启用sendfile功能,sendfile功能用于读写函数中减少拷贝,也就是linux的0拷贝
sendfile on;

3:指定保持连接的超时时长,0表示禁止使用长连接,默认为65秒
keepalive_timeout 65;

4:指定长连接上响应客户端请求的最大数量,默认为100
keepalive_requests 100;

5:指明向客户端发送响应报文的超时时长,如果客户端没有接受,那么就关闭连接
send_timeout 60s;

6:指明客户端请求报文的body部分的数据,设置缓冲区大小,超出16K大小会被存储在硬盘上
client_body_buffer_size 16k;

7:指定响应报文的传输速率,默认为0,不做限制
limit_rate 0;

8:指明启用AIO
aio off;

9:指定配置一个虚拟主机
server { }

(4)server配置段
1:指明socket的监听选项,有下面三种常用情况
listen address[:port] [default_server] [ssl] [backlog=number] [rcvbuf=size] [sndbuf=size]
listen port [default_server] [ssl]
listen unix:path [default_server] [ssl]

port:指明端口
default_server:指定这个虚拟主机是默认的虚拟主机
ssl:限制只能通过ssl连接提供服务
backlog:后援队列的长度
rcvbuf:接受缓冲大小
sndbuf:发送缓冲大小

2:指明当前server的主机名,主机名可以并排写,有四种定义主机名的格式,但是优先级有区别
server_name www.uplooking.com
精确定义主机名,例如:www.uplooking.com 优先级第一
左通配定义主机名:例如:*.uplooking.com 优先级第二
右通配定义主机名:例如:www.uplooking.* 优先级第三
使用正则表达式匹配主机名:例如:~^.*/.uplooking/..*$ 优先级第四

3:指明站点路径,配置文件默认是相对路径,可以写绝对路径/usr/local/nginx/html
root html;

4:在keepalived模式下的连接是否启用TCP_NODELAY选项,TCP有一个默认的delay优化机制,可以在这里将它关闭
tcp_nodelay on

5:指明默认的首页文件
index index.html index.htm;

6:指定错误页面重定向
error_page 404 =200 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}

7:指定匹配的URL,通过用户输入的URL来匹配不同的location,匹配到了,就按照location内部的设置进行响应
location [ = | ~ | ~* | ^~ ] uri {

}

= :URI精确匹配 ,优先级第一
^~ :对于URI的左边进行匹配,不区分字符大小写,优先级第二
~ :模式匹配,正则表达式模式匹配,匹配时候区分大小写,优先级第三
~* :模式匹配,正则表达式模式匹配,匹配时候不区分大小写 ,优先级第三
不带以上四种符号的URI的优先级是第四

(5)location配置段
1:指定路径别名(要与root指令区别开来)
location /i/ {
alias /data/w3/images/;
}
请求:http://www.uplooking.com/i/index.html
资源文件:/data/w3/images/index.html

2:指定访问控制,除了GET方法以外,例如:POST方法,必须是192.168.10.10主机,才能够被响应
limit_except GET {
allow 192.168.10.10;
deny all;
}

Nginx缓存指令

# 指定缓存开启,且最大的文件缓存为1000,非活动的缓存时长为20秒
open_file_cache max=1000 inactive=20s;

# 指定缓存有效性的,默认是60秒
open_file_cache_valid 30s;

# 缓存对象被访问的次数小于2,则被认为是非活动对象
open_file_cache_min_uses 2;

# 是否缓存错误信息
open_file_cache_errors on;

http段
访问控制模块 ngx_http_access_module

location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}

http段
访问认证模块 ngx_http_auth_basic_module

创建basic认证文件
htpasswd -c /etc/nginx/.uplooking_password uplooking

location /uplooking/ {
auth_basic "uplooking Place;"
auth_basic_user_file /etc/nginx/.uplooking_password;
}

http段
基本状态模块 ngx_http_stub_status_module

# 请用统计功能
stub_status;

(四)
Nginx
几个常用的标准模块介绍


ngx_http_ssl_module
(https)

1:指明是否启用的虚拟主机的ssl功能
ssl on | off;

2:指明虚拟主机使用的证书文件
ssl_certificate /usr/local/nginx/conf/cert.pem;

3:指明虚拟主机使用的私钥文件
ssl_certificate_key /usr/local/nginx/conf/cert.key;

4:指明SSL的协议版本
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

5:指明ssl会话的缓存机制
ssl_session_cache shared:SSL:10m;
shared:表明是worker共享的缓存
name:缓存的名称
size:缓存大小的单位是字节,每1MB内存空间可以缓存4000个会话

6:指明ssl会话超时时长
ssl_session_timeout 10m;

ngx_http_log_module
(日志)

1:访问日志路径,记录类型,是否压缩,多长时间刷新一次缓冲
access_log /path/to/log.gz combined gzip flush=5m;

2:指定日志记录类型
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';

3:指定日志缓冲的信息,也就是指定文件描述符
open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

ngx_http_rewrite_module
(重定向)

1:指定rewrite规则
rewrite regex replacement [flag];

什么是rewrite规则:If the specified regular expression matches a request URI, URI is changed as specified in the replacement string. The rewrite directives are executed sequentially in order of their appearance in the configuration file. It is possible to terminate further processing of the directives using flags. If a replacement string starts with “http://”, “https://”, or “$scheme”, the processing stops and the redirect is returned to a client.

人工翻译(可以打赏哦!!!):如果regex匹配到用户访问的URI,那么用户访问的URI就会被替换为replacement所指定的string。这个replacement所指定的string会继续向后执行,但是执行到哪里结束会给flags这个参数所决定。如果这个replacement是“http://”, “https://”, 或者是“$scheme”开头的话,那么rewrite将不会向后执行,会直接终止并返回给客户端

rewrite的工作法则:
1:rewrite实现重写操作,匹配URI可以使用正则表达式匹配,替换可以使用正则表达式的后向引用
2:如果在location中存在多个rewrite规则会自上而下逐个被匹配检查,可以使用flag参数控制
3:如果replacement string是以“http://”, “https://”, 或者是“$scheme”开头的话,则替换结果会直接以重定向方式返回给用户

flag参数详解:
1:last:表示结束本轮rewrite规则从上之下进行检查,而是从最开始从新循环检查,且请求结果不会返回给客户端(状态码为:200)
2:break:重写完成后不会对将前URI进行后续的匹配检查,直接将URI请求的资源返回给客户端(状态码为:200)
3:redirect:重定向完成后以临时重定向的方式直接返回新的URL给客户端,客户端再对新的URL发起请求(状态码为:302)
4:permanent:重定向成后以永久重定向的方式直接返回新的URL给客户端,客户端在对新的URL发起请求(状态码为:301)

避免死循环匹配:(加一个break)
location / {
root /app;
index index.html index.htm;
rewrite (.*)\.htm$ $1.html break;
}

location ~* \.html$ {
root /app;
index index.html index.htm;
rewrite (.*)\.html$ $1.htm break;
}

2:指定rewrite是否记录到日志,如果启用,这些rewrite日志会记录到错误日志中
rewrite_log on | off;

3:设置条件判断,如果条件满足,执行指定的指令
判断表达式:
==:精确等于
!=:不等于
~:模式匹配,区分字母大小写
~*:模式匹配,不区分字母大小写
!~:模式不匹配,区分字母大小写
!~*:模式不匹配,不区分字母大小写

检查file或directory的属性:
-f, !-f:如果文件存在
-d, !-d: 如果目录存在
-e, !-e:如果文件或目录或链接存在
-x , !-x:如果文件可执行

例如:
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}

if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
set $id $1;
}

if ($request_method = POST) {
return 405;
}

if ($slow) {
limit_rate 10k;
}

if ($invalid_referer) {
return 403;
}

4:自定义变量
set $variable value

例如:
set $hello "ni hao"

5:指定返回的状态码或URL,停止处理URI匹配过程
return code

例如:
if ($invalid_referer) {
return 403 "<p> wrong page </p>"
}

ngx_http_gzip_module
(压缩)

功用:用户压缩文本资源

1:启用gzip压缩功能
gzip on | off;

2:指定压缩比例,1-9,默认为1
gzip_comp_level level;

3:开启压缩功能的最小的长度
gzip_min_length length;

4:设定协议的最小版本以上都可以压缩
gzip_http_version 1.0 | 1.1;

5:设定压缩的资源内容类型,默认为text/html
gzip_types mime-type …;

6:如果Nginx是方向代理如果进行压缩
gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any …;

例如:
gzip on
gzip_http_version 1.1
gzip_disable msle6
gzip_min_lengh 1000
gzip_types text/plain text/css text/js application/xml
gzip_proxied expired no-cache no-store private auth;

ngx_http_fastcgi_module
(fastcgi功能)

对于LAMP来说:实现fastcgi协议的模块为proxy_fastcgi_module,
对于LNMP来说:实现fastcgi协议的模块为ngx_http_fastcgi_module,

fastcgi模块的指令说明:

1:在Nginx中指定php-fpm服务器监听的地址和端口
fastcgi_pass address;
例如:fastcgi_pass 127.0.0.1:9000;

2:定义fastcgi应用的主页名称
fastcgi_index name;
例如:fastcgi_index index.php;

3:传递给php-fpm服务器参数及其值
fastcgi_param parameter value [if_not_empty];
例如:fastcgi_param SCRIPT_FILENAME /apps/php/$fastcgi_script_name;
需要导入fastcgi_param参数文件,用include fastcgi_params; 这个 fastcgi_param文件里面有各种的变量,其中就有$fastcgi_script_name。

4:fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

path:指明缓存文件系统路径,用于缓存文件数据,在这个路径下会有n级结构,实现对文件数据的快速查找,使用的hash算法

max_size=size:此路径下指定多大的空间用于缓存数据

levels=#:指定缓存目录的层级结构
例如:levels=1:2 表示:一级目录的名称为1个字符,二级目录的名称为2个字符

keys_zone=name:size:指定磁盘上用于存储value的存储空间名称、大小

inactive=time:指定非活动时间

max_size=size:指定存储的空间大小

注意:这个只能用于http上下文(/var/cache/nginx_fastcgi目录需要先创建好)
例如:在http的上下文中指定:fastcgi_cache_path /var/cache/nginx_fastcgi levels=1:2:3 keys_zone=fcgi_cache:10m inactive=3h;
在一个fastcgi的location中调用这个fastcgi_cache存储空间名
例如:
location ~ \.php$ {
fastcgi_cache fcgi_cache;
}

5:是否启用cache功能,如何启用,数据缓存在哪个cache中
fastcgi_cache zone | off;
例如:在使用fastcgi的location中添加:fastcgi_cache fcgicache; 指明调用的缓存的名字

6:指明在缓存中使用什么作为k/v键值对中的key
fastcgi_cache_key string;
例如:在使用fastcgi的location中添加:fastcgi_cache_key $request_uri; 指明以用户请求的uri为key

7:指明缓存哪些请求方法的数据
fastcgi_cache_methods GET | HEAD | POST …;
例如:fastcgi_cache_methods GET

8:指定请求匹配的最小次数,大于最小次数才会缓存
fastcgi_cache_min_uses number;
例如:fastcgi_cache_min_uses 5;

9:指明对应的响应码缓存的时间,没有定义是不会缓存的
fastcgi_cache_valid [code …] time;
例如:
fastcgi_cache_valid 200 30s;
fastcgi_cache_valid 301 302 1m;
fastcgi_cache_valid any 10s;

注意:用使用缓存机制,需要在location中指定如下三个指令
fastcgi_cache
fastcgi_cache_key
fastcgi_cache_valid

在Nginx中使用ngx_http_fastcgi_module示例
location ~ \.php$ {
# 将客户端请求的URI从$fastcgi_script_name变量中取出来,且通过fastcgi发送给php服务器,fastcgi://192.168.23.201:9000/apps/php/$fastcgi_script_name。那么PHP服务器就会在本地的文件系统去找/apps/php/$fastcgi_script_name资源。
fastcgi_pass 192.168.23.201:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /apps/php/$fastcgi_script_name;
include fastcgi_params;
# 指明缓存的键,这里存储的是key值
fastcgi_cache_key $request_uri;
# 调用缓存的磁盘存储空间,这里存储的是value值
fastcgi_cache fcgi_cache;
# 指定可以缓存的状态码
fastcgi_cache_valid 200 30s;
fastcgi_cache_valid 301 302 1m;
fastcgi_cache_valid any 10s;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: