Nginx的工做原理和配置詳解

1、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.php

Nginx是一款免費的、開源的、高性能的HTTP服務器、反向代理服務器、郵件代理服務器。是由俄羅斯人Igor Sysoev人在2002研發成功的,2004年發佈初版公共穩定版。到目前爲止,Ngnix市場所佔額是12.18%。Nginx以它的高性能,穩定性,豐富特性(第三方模塊的支持),配置簡單和較低的資源消耗著稱。html

Nginx的工做流程:

Nginx會按需同時運行多個進程:一個主進程(master)和幾個工做進程(worker),配置了緩存時還會有緩存加載器進程(cache loader)和緩存管理器進程(cache manager)等。全部進程均是僅含有一個線程,並主要經過「共享內存」的機制實現進程間通訊。主進程以root用戶身份運行,而worker、cache loader和cache manager均應以非特權用戶身份運行。 python

主進程主要完成以下工做:

1. 讀取並驗正配置信息;nginx

2. 建立、綁定及關閉套接字;web

3. 啓動、終止及維護worker進程的個數;算法

4. 無須停止服務而從新配置工做特性;數據庫

5. 控制非中斷式程序升級,啓用新的二進制程序並在須要時回滾至老版本;vim

6. 從新打開日誌文件,實現日誌滾動;後端

7. 編譯嵌入式perl腳本; 緩存

worker進程主要完成的任務包括:

1. 接收、傳入並處理來自客戶端的鏈接;

2. 提供反向代理及過濾功能;

3. nginx任何能完成的其它任務;

cache loader進程主要完成的任務包括:

1. 檢查緩存存儲中的緩存對象;

2. 使用緩存元數據創建內存數據庫;

cache manager進程的主要任務:

1. 緩存的失效及過時檢驗;

具體,更詳細的內容參照官網:nginx.org

2、安裝配置nginx

安裝:

說明: 這裏所使用的操做系統類型,CentOS 6.5

rpm方式裝:

下載官方製做好的rpm包,直接安裝。下載地址:http://nginx.org/packages/

源碼安裝:

一、解決依賴關係

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

二、安裝

首先添加用戶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

1

配置文件簡單說明:

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創建會話等。

一、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/(.*)$ /p_w_picpaths/$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

4

5

6

7

8

二、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.

10

12

四、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

結果展現:

22

21

相關文章
相關標籤/搜索