nginx安裝(yum),Nginx安裝(編譯),Nginx配置文件,Nginx架構分析

Nginx安裝(yum)

yum安裝Nginx,需要使用到epel-release源。這個可以先通過yum安裝源。不過這個源安裝的Nginx可能版本比較老。

你也可以自己弄一個Nginx源

寫一個文件:

[root@shuai-01 ~]# vim /etc/yum.repos.d/nginx.repo

[nginx]
name=nginx repo 
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ 
gpgcheck=0 
enabled=1

這時yum list 查看,Nginx源生效:

[root@shuai-01 ~]# yum list |grep nginx
collectd-nginx.x86_64                     5.8.0-4.el7                  epel     
munin-nginx.noarch                        2.0.40-4.el7                 epel     
nextcloud-nginx.noarch                    10.0.4-2.el7                 epel     
nginx.x86_64                              1:1.14.0-1.el7_4.ngx         nginx    
nginx-all-modules.noarch                  1:1.12.2-2.el7               epel     
nginx-debug.x86_64                        1:1.8.0-1.el7.ngx            nginx    
nginx-debuginfo.x86_64                    1:1.14.0-1.el7_4.ngx         nginx    
nginx-filesystem.noarch                   1:1.12.2-2.el7               epel     
nginx-mod-http-geoip.x86_64               1:1.12.2-2.el7               epel     
nginx-mod-http-image-filter.x86_64        1:1.12.2-2.el7               epel     
nginx-mod-http-perl.x86_64                1:1.12.2-2.el7               epel     
nginx-mod-http-xslt-filter.x86_64         1:1.12.2-2.el7               epel     
nginx-mod-mail.x86_64                     1:1.12.2-2.el7               epel     
nginx-mod-stream.x86_64                   1:1.12.2-2.el7               epel     
nginx-module-geoip.x86_64                 1:1.14.0-1.el7_4.ngx         nginx    
nginx-module-geoip-debuginfo.x86_64       1:1.14.0-1.el7_4.ngx         nginx    
nginx-module-image-filter.x86_64          1:1.14.0-1.el7_4.ngx         nginx    
nginx-module-image-filter-debuginfo.x86_64
                                          1:1.14.0-1.el7_4.ngx         nginx    
nginx-module-njs.x86_64                   1:1.14.0.0.2.4-1.el7_4.ngx   nginx    
nginx-module-njs-debuginfo.x86_64         1:1.14.0.0.2.4-1.el7_4.ngx   nginx    
nginx-module-perl.x86_64                  1:1.14.0-1.el7_4.ngx         nginx    
nginx-module-perl-debuginfo.x86_64        1:1.14.0-1.el7_4.ngx         nginx    
nginx-module-xslt.x86_64                  1:1.14.0-1.el7_4.ngx         nginx    
nginx-module-xslt-debuginfo.x86_64        1:1.14.0-1.el7_4.ngx         nginx    
nginx-nr-agent.noarch                     2.0.0-12.el7.ngx             nginx    
owncloud-nginx.noarch                     9.1.5-1.el7                  epel     
pcp-pmda-nginx.x86_64                     3.12.2-5.el7                 base     
python2-certbot-nginx.noarch              0.27.1-1.el7                 epel     

yum 安裝:

[root@shuai-01 ~]# yum install -y nginx

啓動Nginx:

[root@shuai-01 ~]# systemctl start nginx
[root@shuai-01 ~]# ps aux |grep nginx
root       5606  0.0  0.0  46368   968 ?        Ss   13:49   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx      5607  0.0  0.1  46768  1932 ?        S    13:49   0:00 nginx: worker process
root       5609  0.0  0.0 112680   976 pts/1    R+   13:49   0:00 grep --color=auto nginx

關閉防火牆,selinux,就可以瀏覽器訪問了。

查看版本和編譯參數:

[root@shuai-01 ~]# nginx -V
nginx version: nginx/1.14.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --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-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

Nginx安裝(源碼)

先把原來yum 安裝的remove掉

[root@shuai-01 nginx-1.14.0]# yum remove nginx

下載源碼包:

[root@shuai-01 ~]# cd /usr/local/src/
[root@shuai-01 src]# wget http://nginx.org/download/nginx-1.14.0.tar.gz

解壓包:

[root@shuai-01 src]# tar zxvf nginx-1.14.0.tar.gz

編譯安裝:

[root@shuai-01 nginx-1.14.0]# ./configure --prefix=/usr/local/nginx

[root@shuai-01 nginx-1.14.0]# make

[root@shuai-01 nginx-1.14.0]# make install

啓動:

[root@shuai-01 nginx-1.14.0]# /usr/local/nginx/sbin/nginx 
[root@shuai-01 nginx-1.14.0]# ps aux |grep nginx
root       8392  0.0  0.0  20504   608 ?        Ss   14:15   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nobody     8393  0.0  0.1  20948  1340 ?        S    14:15   0:00 nginx: worker process
root       8395  0.0  0.0 112680   976 pts/1    R+   14:15   0:00 grep --color=auto nginx

這個時候想要停止Nginx,只能killall Nginx

可以通過啓動腳本來管理:

[root@shuai-01 nginx-1.14.0]# vi /etc/init.d/nginx

#!/bin/bash
# chkconfig: - 30 21
# description: http service.
# Source Function Library
. /etc/init.d/functions
# Nginx Settings

NGINX_SBIN="/usr/local/nginx/sbin/nginx"
NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
NGINX_PID="/usr/local/nginx/logs/nginx.pid"
RETVAL=0
prog="Nginx"

start() 
{
    echo -n $"Starting $prog: "
    mkdir -p /dev/shm/nginx_temp
    daemon $NGINX_SBIN -c $NGINX_CONF
    RETVAL=$?
    echo
    return $RETVAL
}

stop() 
{
    echo -n $"Stopping $prog: "
    killproc -p $NGINX_PID $NGINX_SBIN -TERM
    rm -rf /dev/shm/nginx_temp
    RETVAL=$?
    echo
    return $RETVAL
}

reload()
{
    echo -n $"Reloading $prog: "
    killproc -p $NGINX_PID $NGINX_SBIN -HUP
    RETVAL=$?
    echo
    return $RETVAL
}

restart()
{
    stop
    start
}

configtest()
{
    $NGINX_SBIN -c $NGINX_CONF -t
    return 0
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  reload)
        reload
        ;;
  restart)
        restart
        ;;
  configtest)
        configtest
        ;;
  *)
        echo $"Usage: $0 {start|stop|reload|restart|configtest}"
        RETVAL=1
esac

exit $RETVAL

腳本啓動:

[root@shuai-01 nginx-1.14.0]# /etc/init.d/nginx start
Reloading systemd:                                         [  確定  ]
Starting nginx (via systemctl):                            [  確定  ]
[root@shuai-01 nginx-1.14.0]# !ps
ps aux |grep nginx
root       8491  0.0  0.0  20504   604 ?        Ss   14:25   0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nobody     8492  0.0  0.1  20944  1336 ?        S    14:25   0:00 nginx: worker process
root       8494  0.0  0.0 112680   976 pts/1    R+   14:25   0:00 grep --color=auto nginx

設置開機自啓動:

[root@shuai-01 nginx-1.14.0]# chkconfig --add nginx
[root@shuai-01 nginx-1.14.0]# chkconfig nginx on
[root@shuai-01 nginx-1.14.0]# chkconfig --list

注意:該輸出結果只顯示 SysV 服務,並不包含原生 systemd 服務。SysV 配置數據可能被原生 systemd 配置覆蓋。 
      如果您想列出 systemd 服務,請執行 'systemctl list-unit-files'。
      欲查看對特定 target 啓用的服務請執行
      'systemctl list-dependencies [target]'。

mysqld         	0:關	1:關	2:開	3:開	4:開	5:開	6:關
netconsole     	0:關	1:關	2:關	3:關	4:關	5:關	6:關
network        	0:關	1:關	2:開	3:關	4:開	5:開	6:關
nginx          	0:關	1:關	2:開	3:開	4:開	5:開	6:關

Nginx的配置文件

編譯安裝的Nginx的配置文件在: /usr/local/nginx/conf

[root@shuai-01 nginx-1.14.0]# cd /usr/local/nginx/conf
[root@shuai-01 conf]# ls
fastcgi.conf            koi-win             scgi_params
fastcgi.conf.default    mime.types          scgi_params.default
fastcgi_params          mime.types.default  uwsgi_params
fastcgi_params.default  nginx.conf          uwsgi_params.default
koi-utf                 nginx.conf.default  win-utf

配置文件結構:
全局配置(user、worker_processes、error_log、pid)
events(網絡連接相關,worker_connections)
http(最重要的部分,大部分功能都放這裏)
server(虛擬主機相關)
location(server裏面)

全局部分:

user  nobody;//Nginx以那一個用戶的身份來運行work進程
worker_processes  1;//用來定義work進程有幾個,一般的這個數字和你的CPU核數來決定的,一個CPU核數跑一個work

error_log  logs/error.log crit ;//前面日誌存在哪 ,後面的用來定義日誌記錄的級別。crit是記錄級別比較高的,只會記錄一些重要的
pid        logs/nginx.pid;//pid的位置

https://coding.net/u/aminglinux/p/nginx/git/blob/master/3z/global.md
events部分(和網絡相關的):

worker_connections  1024;//每一個work允許最大的連接,最大數是65535
accept_mutex on;//當某一個時刻只有一個網絡連接請求服務器時,服務器上有多個睡眠的進程會被同時叫醒,這樣會損耗一定的服務器性能。Nginx中的accept_mutex設置爲on,將會對多個Nginx進程(worker processer)接收連接時進行序列化,防止多個進程爭搶資源。默認就是on。
multi_accept on;//nginx worker processer可以做到同時接收多個新到達的網絡連接,前提是把該參數設置爲on。默認爲off,即每個worker process一次只能接收一個新到達的網絡連接。

use epoll;
Nginx服務器提供了多個事件驅動器模型來處理網絡消息。
其支持的類型有:select、poll、kqueue、epoll、rtsing、/dev/poll以及eventport。
* select:只能在Windows下使用,這個事件模型不建議在高負載的系統使用
* poll:Nginx默認首選,但不是在所有系統下都可用
* kqueue:這種方式在FreeBSD 4.1+, OpenBSD2.9+, NetBSD 2.0, 和 MacOS X系統中是最高效的	
* epoll: 這種方式是在Linux 2.6+內核中最高效的方式
* rtsig:實時信號,可用在Linux 2.2.19的內核中,但不適用在高流量的系統中
* /dev/poll: Solaris 7 11/99+,HP/UX 11.22+, IRIX 6.5.15+, and Tru64 UNIX 5.1A+操作系統最高效的方式	
* eventport: Solaris 10最高效的方式

http配置項:

官方文檔 http://nginx.org/en/docs/

參考鏈接: https://segmentfault.com/a/1190000012672431

參考鏈接: https://segmentfault.com/a/1190000002797601

參考鏈接:http的header https://kb.cnblogs.com/page/92320/

MIME-Type

include mime.types; //cat conf/mime.types
定義nginx能識別的網絡資源媒體類型(如,文本、html、js、css、流媒體等)

default_type  application/octet-stream;

定義默認的type,如果不定義改行,默認爲text/plain.

log_format //訪問日誌格式

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

其中main爲日誌格式的名字,後面的爲nginx的內部變量組成的一串字符串。

access_log logs/access.log main;

定義日誌的路徑以及採用的日誌格式,該參數可以在server配置塊中定義。

sendfile on;

是否調用sendfile函數傳輸文件,默認爲off,使用sendfile函數傳輸,可以減少user mode和kernel mode的切換,從而提升服務器性能。
對於普通應用設爲 on,如果用來進行下載等應用磁盤IO重負載應用,可設置爲off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。

sendfile_max_chunk 128k;

該參數限定Nginx worker process每次調用sendfile()函數傳輸數據的最大值,默認值爲0,如果設置爲0則無限制。

tcp_nopush on;

當tcp_nopush設置爲on時,會調用tcp_cork方法進行數據傳輸。
使用該方法會產生這樣的效果:當應用程序產生數據時,內核不會立馬封裝包,而是當數據量積累到一定量時纔會封裝,然後傳輸。這樣有助於解決網絡堵塞問題。
默認值爲on。舉例:快遞員收快遞、發快遞,包裹累積到一定量纔會發,節省運輸成本。

keepalive_timeout 65 60;

該參數有兩個值,第一個值設置nginx服務器與客戶端會話結束後仍舊保持連接的最長時間,單位是秒,默認爲75s。
第二個值可以省略,它是針對客戶端的瀏覽器來設置的,可以通過curl -I看到header信息中有一項Keep-Alive: timeout=60,如果不設置就沒有這一項。
第二個數值設置後,瀏覽器就會根據這個數值決定何時主動關閉連接,Nginx服務器就不操心了。但有的瀏覽器並不認可該參數。

send_timeout

這個超時時間是發送響應的超時時間,即Nginx服務器向客戶端發送了數據包,但客戶端一直沒有去接收這個數據包。
如果某個連接超過send_timeout定義的超時時間,那麼Nginx將會關閉這個連接。

client_max_body_size 10m;

瀏覽器在發送含有較大HTTP包體的請求時,其頭部會有一個Content-Length字段,client_max_body_size是用來限制Content-Length所示值的大小的。
這個限制包體的配置不用等Nginx接收完所有的HTTP包體,就可以告訴用戶請求過大不被接受。會返回413狀態碼。
例如,用戶試圖上傳一個1GB的文件,Nginx在收完包頭後,發現Content-Length超過client_max_body_size定義的值,
就直接發送413(Request Entity Too Large)響應給客戶端。

gzip on;

是否開啓gzip壓縮。

gzip_min_length 1k;

設置允許壓縮的頁面最小字節數,頁面字節數從header頭得content-length中進行獲取。默認值是20。建議設置成大於1k的字節數,小於1k可能會越壓越大。

gzip_buffers 4 16k;

設置系統獲取幾個單位的buffer用於存儲gzip的壓縮結果數據流。4 16k代表分配4個16k的buffer。

gzip_http_version 1.1;

用於識別 http 協議的版本,早期的瀏覽器不支持 Gzip 壓縮,用戶會看到亂碼,所以爲了支持前期版本加上了這個選項。
如果你用了Nginx反向代理並期望也啓用Gzip壓縮的話,由於末端通信是http/1.1,故請設置爲 1.1。

gzip_comp_level 6;

gzip壓縮比,1壓縮比最小處理速度最快,9壓縮比最大但處理速度最慢(傳輸快但比較消耗cpu)

gzip_types mime-type ... ;

匹配mime類型進行壓縮,無論是否指定,”text/html”類型總是會被壓縮的。
在conf/mime.conf裏查看對應的type。

示例:gzip_types text/plain application/x-javascript text/css text/html application/xml;

gzip_proxied any;

Nginx作爲反向代理的時候啓用,決定開啓或者關閉後端服務器返回的結果是否壓縮,匹配的前提是後端服務器必須要返回包含”Via”的 header頭。
以下爲可用的值:
off - 關閉所有的代理結果數據的壓縮
expired - 啓用壓縮,如果header頭中包含 “Expires” 頭信息
no-cache - 啓用壓縮,如果header頭中包含 “Cache-Control:no-cache” 頭信息
no-store - 啓用壓縮,如果header頭中包含 “Cache-Control:no-store” 頭信息
private - 啓用壓縮,如果header頭中包含 “Cache-Control:private” 頭信息
no_last_modified - 啓用壓縮,如果header頭中不包含 “Last-Modified” 頭信息
no_etag - 啓用壓縮 ,如果header頭中不包含 “ETag” 頭信息
auth - 啓用壓縮 , 如果header頭中包含 “Authorization” 頭信息
any - 無條件啓用壓縮
Copy

gzip_vary on;

和http頭有關係,會在響應頭加個 Vary: Accept-Encoding ,可以讓前端的緩存服務器緩存經過gzip壓縮的頁面,例如,用Squid緩存經過Nginx壓縮的數據。

server配置項:

nginx.conf server部分配置
server{} 包含在http{}內部,每一個server{}都是一個虛擬主機(站點)。

以下爲nginx.conf配置文件中server{}部分的內容。

    server {
    listen       80;  //監聽端口爲80,可以自定義其他端口,也可以加上IP地址,如,listen 127.0.0.1:8080;
    server_name  localhost; //定義網站域名,可以寫多個,用空格分隔。
    #charset koi8-r; //定義網站的字符集,一般不設置,而是在網頁代碼中設置。
    #access_log  logs/host.access.log  main; //定義訪問日誌,可以針對每一個server(即每一個站點)設置它們自己的訪問日誌。

    ##在server{}裏有很多location配置段
    location / {
        root   html;  //定義網站根目錄,目錄可以是相對路徑也可以是絕對路徑。
        index  index.html index.htm; //定義站點的默認頁。
    }

    #error_page  404              /404.html;  //定義404頁面

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;  //當狀態碼爲500、502、503、504時,則訪問50x.html
    location = /50x.html {
        root   html;  //定義50x.html所在路徑
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #定義訪問php腳本時,將會執行本location{}部分指令
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;  //proxy_pass後面指定要訪問的url鏈接,用proxy_pass實現代理。
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;  //定義FastCGI服務器監聽端口與地址,支持兩種形式,1 IP:Port, 2 unix:/path/to/sockt
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;  //定義SCRIPT_FILENAME變量,後面的路徑/scripts爲上面的root指定的目錄
    #    include        fastcgi_params; //引用prefix/conf/fastcgi_params文件,該文件定義了fastcgi相關的變量
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    # 
    #location ~ /\.ht {   //訪問的url中,以/.ht開頭的,如,www.example.com/.htaccess,會被拒絕,返回403狀態碼。
    #    deny  all;  //這裏的all指的是所有的請求。
    #}
}


# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
#    listen       8000;  //監聽8000端口
#    listen       somename:8080;  //指定ip:port
#    server_name  somename  alias  another.alias;  //指定多個server_name

#    location / {
#        root   html;
#        index  index.html index.htm;
#    }
#}


# HTTPS server
#
#server {
#    listen       443 ssl;  //監聽443端口,即ssl
#    server_name  localhost;

### 以下爲ssl相關配置
#    ssl_certificate      cert.pem;    //指定pem文件路徑
#    ssl_certificate_key  cert.key;  //指定key文件路徑

#    ssl_session_cache    shared:SSL:1m;  //指定session cache大小
#    ssl_session_timeout  5m;  //指定session超時時間
#    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;   //指定ssl協議
#    ssl_ciphers  HIGH:!aNULL:!MD5;  //指定ssl算法
#    ssl_prefer_server_ciphers  on;  //優先採取服務器算法
#    location / {
#        root   html;
#        index  index.html index.htm;
#    }
#}

Nginx架構分析

Nginx模塊化
Nginx基於模塊化設計,每個模塊是一個功能實現,分佈式開發,團隊協作
核心模塊、標準HTTP模塊、可選HTTP模塊、郵件模塊、第三方模塊
編譯後的源碼目錄objs/ngx_modules.c
https://coding.net/u/aminglinux/p/nginx/git/blob/master/4z/module.md

Nginx的web請求機制
並行處理:多進程、多線程、異步
https://coding.net/u/aminglinux/p/nginx/git/blob/master/4z/IO.md
nginxweb請求機制:異步非阻塞

Nginx事件驅動模型
https://coding.net/u/aminglinux/p/nginx/git/blob/master/4z/event.md

設計架構概覽
Nginx基於模塊化設計、基於事件驅動模型處理請求、主進程和工作進程
https://coding.net/u/aminglinux/p/nginx/git/blob/master/4z/jg.md
主進程主要功能是對外通信,對內子進程管理,讀配置文件,綁定sock,接收啓動,重啓,關閉操作。
子進程主要功能接收客戶端請求,處理請求,與後端服務器通信,接收主進程命令。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章