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

Nginx的工作原理和配置详解

2014-09-26 00:44 387 查看

一、Nginx简介

Nginx (pronounced engine-x) is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Igor Sysoev started development of Nginx in 2002, with the first public release in 2004. Nginx now hosts nearly12.18% (22.2M) of active sites across all domains. Nginx is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.Nginx是一款免费的、开源的、高性能的HTTP服务器、反向代理服务器、邮件代理服务器。是由俄罗斯人Igor Sysoev人在2002研发成功的,2004年发布第一版公共稳定版。到目前为止,Ngnix市场所占额是12.18%。Nginx以它的高性能,稳定性,丰富特性(第三方模块的支持),配置简单和较低的资源消耗著称。

Nginx的工作流程:

Nginx会按需同时运行多个进程:一个主进程(master)和几个工作进程(worker),配置了缓存时还会有缓存加载器进程(cache loader)和缓存管理器进程(cache manager)等。所有进程均是仅含有一个线程,并主要通过“共享内存”的机制实现进程间通信。主进程以root用户身份运行,而worker、cache loader和cache manager均应以非特权用户身份运行。

主进程主要完成如下工作:

1. 读取并验正配置信息;
2. 创建、绑定及关闭套接字;
3. 启动、终止及维护worker进程的个数;
4. 无须中止服务而重新配置工作特性;
5. 控制非中断式程序升级,启用新的二进制程序并在需要时回滚至老版本;
6. 重新打开日志文件,实现日志滚动;
7. 编译嵌入式perl脚本;

worker进程主要完成的任务包括:

1. 接收、传入并处理来自客户端的连接;
2. 提供反向代理及过滤功能;
3. nginx任何能完成的其它任务;

cache loader进程主要完成的任务包括:

1. 检查缓存存储中的缓存对象;
2. 使用缓存元数据建立内存数据库;

cache manager进程的主要任务:

1. 缓存的失效及过期检验;
具体,更详细的内容参照官网:nginx.org

二、安装配置nginx

安装:

说明: 这里所使用的操作系统类型,CentOS 6.5

rpm方式装:

下载官方制作好的rpm包,直接安装。下载地址:http://nginx.org/packages/

源码安装:

1、解决依赖关系

# yum groupinstall "Development Tools" "Server Platform Deveopment" -y
yum install openssl-devel pcre-devel -y

2、安装

首先添加用户nginx,实现以之运行nginx服务进程:
# groupadd -r nginx
# useradd -r -g nginx nginx

接着开始编译和安装:
# ./configure \
--prefix=/usr/local/nginx \   -----> Nginx的安装目录
--error-log-path=/data/applogs/nginx/error.log \	-----> Nginx的错误日志
--http-log-path=/data/applogs/nginx/access.log \	-----> Ngnix的访问日志
--pid-path=/var/run/nginx/nginx.pid  \	-----> Nginx的pid文件
--lock-path=/var/lock/nginx.lock \	-----> Nginx锁文件位置
--user=nginx \	-----> Nginx进程运行时的用户
--group=nginx \	-----> Nginx进程运行时的组
--with-http_ssl_module \	-----> 添加 SSL 模块
--with-http_flv_module \	-----> 添加 flv 格式的模块
--with-http_stub_status_module \	-----> 添加 stub_status 模块
--with-http_gzip_static_module \	-----> 添加 gzip_static 模块
--http-client-body-temp-path=/usr/local/nginx/client/ \	-----> 客户端实体存放位置
--http-proxy-temp-path=/usr/local/nginx/proxy/ \	-----> 代理配置目录
--http-fastcgi-temp-path=/usr/local/nginx/fcgi/ \	-----> fastcgi位置 (php)
--http-uwsgi-temp-path=/usr/local/nginx/uwsgi \	-----> uwsgi位置 (python)
--http-scgi-temp-path=/usr/local/nginx/scgi \		-----> scgi配置的位置
--with-pcre	-----> 支持pcre

# make && make install

配置:

说明:这里使用的安装方式是rmp安装方式。
安装的节点:172.16.10.77



配置文件简单说明:

Nginx的配置有着几个不同的上下文:main、http、server、upstream和location(还有实现邮件服务
反向代理的mail)。
配置语法的格式和定义方式遵循所谓的C风格,因此支持嵌套,还有着逻辑清晰并易于创建、阅读和维
护等优势。

Nginx的代码是由一个核心和一系列的模块组成, 核心主要用于提供Web Server的基本功能,以及Web
和Mail反向代理的功能;
还用于启用网络协议,创建必要的运行时环境以及确保不同的模块之间平滑地进行交互。不过,大多
跟协议相关的功能和某应用特有的功能都是由nginx的模块实现的。
这些功能模块大致可以分为事件模块、阶段性处理器、输出过滤器、变量处理器、协议、upstream和
负载均衡几个类别,这些共同组成了nginx的http功能。
事件模块主要用于提供OS独立的(不同操作系统的事件机制有所不同)事件通知机制如kqueue或epoll等
。
协议模块则负责实现nginx通过http、tls/ssl、smtp、pop3以及imap与对应的客户端建立会话。

在nginx内部,进程间的通信是通过模块的pipeline或chain实现的;
换句话说,每一个功能或操作都由一个模块来实现。例如,压缩、通过FastCGI或uwsgi协议与
upstream服务器通信,以及与memcached建立会话等。

1、nginx提供web服务

[root@localhost nginx]# cat nginx.conf
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
use epoll;
worker_connections  1024;
}

http {
include       /etc/nginx/mime.types;
default_type  application/octet-stream;

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log  /var/log/nginx/access.log  main;

sendfile        on;

keepalive_timeout  65;
server {
listen 80;
add_header X-Via $server_addr;
server_name www.example.com;
location / {
root /usr/share/nginx/html;
index  index.html index.htm;
rewrite ^/imgs/(.*)$ /images/$1 break;  # 重写url
}

location /status {
stub_status on;
}
# 设置用户认证,认证文件需要使用htpasswd命令生成
location /admin {
index index.html;
root /usr/share/nginx/html;
auth_basic           "admin pass";
auth_basic_user_file /etc/nginx/htpasswd;
}

location /bbs {
proxy_pass http://172.16.10.16/; }
}

include /etc/nginx/conf.d/*.conf;
}
结果示例:


















2、nginx反向代理、提供缓存

Nginx的反向代理是由proxy模块实现的。结合upstream模块实现简单的负载均衡。
详细信息参考:http://wiki.nginx.org/Modules
[root@localhost nginx]# cat nginx.conf
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
use epoll;
worker_connections  1024;
}

http {
include       /etc/nginx/mime.types;
default_type  application/octet-stream;

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log  /var/log/nginx/access.log  main;

sendfile        on;

keepalive_timeout  65;
proxy_cache_path /data/cache  levels=1:2   keys_zone=web:10m max_size=512m;
upstream web {
#ip_hash;
server 172.16.10.11:80;
server 172.16.10.9:80;
server 172.16.10.16:80 weight=1;
server 172.16.10.77:8080 backup;
}
server {
listen 80;
add_header X-Via $server_addr;
add_header X-Cache-Status $upstream_cache_status;
server_name www.example.com;
location / {
root /usr/share/nginx/html;
proxy_pass http://web; proxy_cache web;
proxy_cache_valid 200 1d;
proxy_cache_valid 301 302 10m;
proxy_cache_valid any 1m;
index  index.html index.htm;
if ($request_method ~* "PUT") {
proxy_pass http://172.16.10.11; break;
}
}

}

include /etc/nginx/conf.d/*.conf;
}


结果展示:
如果没有缓存数据,会根据调度算法调度到后端的real server.






4、nginx的FastCgi工作模式

# 在对应的server段添加以下,就可实现 fastcgi 代理

location ~ \.php$ {
root /php;
fastcgi_pass 172.16.10.11:9000;
fastcgi_index index.php;
fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
include        fastcgi_params;
}

[root@localhost nginx]# cat fastcgi_params
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# 在172.16.10.11上配置好,php-fpm环境
yum install php-fpm

配置监听端口: /etc/php-fpm.d/www.conf
listen = 172.16.10.11:9000
允许访问端口:注释表示any
;listen.allowed_clients = 127.0.0.1

mkdir /php
vim /php/index.php
<?php
phpinfo();
?>

启动php-fpm
结果展示:





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  工作原理 Nginx