nginx

nginx
nginx是一款輕量級的web服務器/反向代理服務器及電子郵件(IMAP/POP3)代理服務器
nginx是個高性能web和反向代理服務器
nginx由內核和模塊組成
nginx的特性與優點

'特性:
使用epoll  and  kqueue作爲開發模型
在高連接併發的情況下,nginx是apache服務器不錯的替代品,能夠支持高達50000個併發連接數的響應
nginx作爲負載均衡服務器,既可在內部直接支持和PHP程序對外進行服務,也可作爲HTTP代理服務器對外進行服務
採用c語言進行編寫'

'優點:
~~~模塊化設計:模塊可以動態編譯
~~~穩定性高:用於反向代理
~~~節省帶寬:支持GZIP壓縮,可以添加瀏覽器本地緩存的Header頭
~~~配置文件簡單
~~~高併發連接:官方測試能支持5萬併發連接,實際生產環境中跑2-3萬併發連接數
~~~成本低廉:免費使用,購買F5 BIG-IP NetScaler 等硬件負載均衡交換機則需要十多萬至幾十萬人名幣
~~~內置的健康檢查功能:Nginx Proxy後端如果某臺web服務端宕機,不會影響前端訪問
~~~外圍支持好:文檔全,二次開發和模塊較多
~~~支持熱部署:可以不停機重載配置文件
~~~支持事件驅動,AIO (Asycncl ,異步IO)、mmap(Memory Map,內存映射)等性能優化 '

nginx的模塊從結構上分爲核心模塊、基礎模塊和第三方模塊
核心模塊:HTTP模塊、event模塊、mail模塊
基礎模塊:http access模塊、http fastcgl模塊、http proxy模塊、http rewrite模塊
第三方模塊:http upstream模塊、request hash模塊、notice模塊、http access key模塊(自己需要開發的模塊都屬於第三方模塊)
nginx模塊從功能fen'w分爲三類:Handlers(處理器模塊)、Filters(過濾器模塊)、proxies(代理器模塊)

'Handlers(處理器模塊):直接處理請求,進行輸出內容和修改headers信息等操作
Filters(過濾器模塊):主要是對其他處理器模塊輸出的內容進行修改操作,最後由nginx輸出
Proxies(代理器模塊):nginx的HTTP upstream之類的模塊,這些模塊主要與後端一些服務比如fastcgi等操作交互,實現服務代理和負載均衡等功能。'

nginx的安裝

'創建系統用戶nginx'
[root@arongya ~]# useradd -r -M -s /sbin/nologin nginx
[root@arongya ~]# id nginx
uid=998(nginx) gid=996(nginx) groups=996(nginx)
'安裝依賴環境'
[root@arongya ~]# yum -y install pcre-devel openssl openssl-devel gd-devel
[root@arongya ~]# yum -y groups mark install 'Development Tools'
'創建日誌存放目錄'
[root@arongya ~]# mkdir -p /var/log/nginx
[root@arongya ~]# chown -R nginx.nginx /var/log/nginx/
'下載nginx'
[root@arongya ~]# cd /usr/src/
[root@arongya src]# wget http://nginx.org/download/nginx-1.12.0.tar.gz
'編譯安裝'
[root@arongya src]# ls
debug  kernels  nginx-1.12.0.tar.gz
[root@arongya src]# tar xf nginx-1.12.0.tar.gz
[root@arongya src]# cd nginx-1.12.0
[root@arongya nginx-1.12.0]# ./configure \
> --prefix=/usr/local/nginx \
> --user=nginx \
> --group=nginx \
> --with-debug \
> --with-http_ssl_module \
> --with-http_realip_module \
> --with-http_image_filter_module \
> --with-http_gunzip_module \
> --with-http_gzip_static_module \
> --with-http_stub_status_module \
> --http-log-path=/var/log/nginx/access.log \
> --error-log-path=/var/log/nginx/error.log
[root@arongya nginx-1.12.0]# make -j 2 && make install
'配置環境變量'
[root@arongya ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@arongya ~]# source /etc/profile.d/nginx.sh
'啓動nginx'
[root@arongya ~]# nginx 
[root@arongya ~]# ss -antl
State       Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN      0      128     *:80                  *:*                  
LISTEN      0      128     *:22                  *:*                  
LISTEN      0      100    127.0.0.1:25                  *:*                  
LISTEN      0      128    :::22                 :::*                  
LISTEN      0      100       ::1:25                 :::*                  

最後在瀏覽器通過IP訪問,出現如下界面就是正確
nginx

服務控制方式,使用nginx命令

-t   檢查配置文件語法
-v   輸出nginx的版本
-c   指定配置文件的路徑
-s  發送服務控制信號,可選值有stop、quit、 reopen、reload

nginx的配置文件,nginx的基本配置文件在/usr/local/nginx/conf/nginx.conf,nginx.conf的內容分爲以下幾段:
main配置段:全局配置段,其中main配置段中可能包含event配置段
event{}:定義event模型工作特性
http{}:定義http協議相關的配置,要以分號結尾
/usr/local/nginx/conf/nginx.conf修改後的配置文件如下:

[root@arongya conf]# vim nginx.conf
user  nginx;      #'event配置段,指定運行worker進程的用戶和組'
worker_processes  3;      #'啓動n個worker進程,這裏的n爲了避免上下文切換,通常設置爲cpu總核心數,設置幾個人工作'
worker_cpu_affinity  00000001  00000010  00000100;    #'將進程綁定到某cpu中,避免頻繁刷新緩存,優化性能的配置參數'
error_log  logs/error.log;    #'位置 級別;配置錯誤日誌,相對路徑,級別:notice、info'
lock_file   logs/nginx.lock;
pid        logs/nginx.pid;    '指定nginx守護進程的pid文件'
worker_rlimit_nofile 35000;

daemon on;   '#這行是添加的,daemon {on|off};   //是非法以守護進程方式運行nginx,調試時應設置爲off'

events {
    worker_connections  35000;     #'每個進程能夠接受的最大連接數'
        accept_mutex  on;       #'master調度用戶請求至各worker進程使用的負載均衡鎖'
}

http {      '//協議級別'
    include       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  logs/access.log  main;

    sendfile        on;

    keepalive_timeout  65;

    server {        '服務器級別,每個server類似於httpd中的一個<VirtualHost>,定義一個虛擬主機'
        listen       80;
        server_name  localhost;

        access_log  logs/host.access.log  main;

        location /       '請求級別,類似於httpd中的<Location>,用於定義URL與本地文件系統的映射關係'
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        location ~ \.php$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;     //定義反向代理
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

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

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

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

}

網絡連接相關的配置參數

keepalive_timeout number;        '//長連接的超時時長,默認爲75s'
keepalive_requests number;      '//在一個長連接上所能夠允許請求的最大資源數'
keepalive_disable [msie6|safari|none];  '//爲指定類型的UserAgeng禁用長連接'
tcp_nodelay on|off;     '是否對長連接使用TCP_nodelay選項,爲了提升用戶體驗,通常設爲on'
client_header_timeout number;     '//讀取http請求報文首部的超時時長'
client_body_timeout number;        '//讀取http請求報文body部分的超時時長'
send_timeout number;           '發送響應報文的超時時長'

訪問控制,用於location段
allow:設定允許哪臺或哪些主機訪問,多個參數間用空格隔開
deny:設置禁止哪臺或哪些主機訪問,多個參數間用空格隔開

[root@arongya conf]# vim nginx.conf
....
        location / {
            root   html;
            index  index.html index.htm;
            allow 192.168.228.1;
            deny all;
        }
....
[root@arongya conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya conf]# nginx -s reload

如圖:
nginx
**設置拒絕本機訪問***

[root@arongya conf]# vim nginx.conf

       access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            deny 192.168.228.1;
            allow all;
        }
[root@arongya conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya conf]# nginx -s reload

如圖:
nginx
基於用戶認證

[root@arongya ~]# cd /usr/local/nginx/
[root@arongya nginx]# mkdir auth
[root@arongya nginx]# cd auth
[root@arongya auth]# pwd
/usr/local/nginx/auth
[root@arongya auth]# yum provides *bin/htpasswd
[root@arongya auth]# yum -y install httpd-tools
[root@arongya auth]# htpasswd -c -m /usr/local/nginx/auth/.user_auth_file tom   '這裏的密碼爲加密後的密碼串,建議用htpasswd來創建此文件'
New password:             '此處設的密碼是"yaoxiaorong!",可設爲自己想設的密碼'
Re-type new password: 
Adding password for user tom
[root@arongya auth]# cat /usr/local/nginx/auth/.user_auth_file 
tom:$apr1$VBVYAKxN$5wQz/LPtuebYWeWRwqnjq/
[root@arongya auth]# vim /usr/local/nginx/conf/nginx.conf
.....
        location / {
            root   html;
            index  index.html index.htm;
            auth_basic "welcome to there";
            auth_basic_user_file ../auth/.user_auth_file;     '路徑要帶上絕對路徑,或者在/usr/local/nginx的相對路徑'
        }
.....
[root@arongya auth]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya auth]# nginx -s reload

如圖:
nginx
https配置

'openssl實現私有CA:CA的配置文件:/etc/pki/tls/openssl.cnf'
'CA生成一對密鑰'
[root@arongya ~]# cd /etc/pki/CA
'生成密鑰,括號必須要'
[root@arongya CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)
Generating RSA private key, 2048 bit long modulus
..........+++
............................................................................................................+++
e is 65537 (0x10001)
'提取公鑰'
[root@arongya CA]# openssl rsa -in private/cakey.pem -pubout
writing RSA key
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0BlxNlixtsocqmF/DRHd
XhwarlksT+xpcaEHEdsawhY6OAR3eqC4zwXKp5SwhnI+fm8/u8+wRqaNQfYSsJjo
hn6TchI8jUKhPfI0AyJsJFCAu/n4TDLVZeJhOLYxkDw7SlyTcqMcjVEnoLboT3kK
OYjFSnEd6436B9N/kElJlizybmU/ThnzsgHWpd382QkxfDRa/yoE+jNgGfKzoSYQ
Rsr403+pvCuj7M/EdxEeUvl364CmUVk8y22W8kxKXq40K4/+M5Wb+6Io94ENwwoy
kh75h0aVbSN3o+AdD/ulxpv8IgC80JfXScjvfWKEBxYcPnuBo8QvLmzVve7vHSrJ
jQIDAQAB
-----END PUBLIC KEY-----

CA生成自簽署證書

[root@arongya CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn
State or Province Name (full name) []:hb
Locality Name (eg, city) [Default City]:wh
Organization Name (eg, company) [Default Company Ltd]:www.yaoxiaorong.com
Organizational Unit Name (eg, section) []:www.yaoxiaorong.com
Common Name (eg, your name or your server's hostname) []:www.yaoxiaorong.com
Email Address []:[email protected]

'讀出cacert.pem證書的內容'
[root@arongya CA]# openssl x509 -text -in cacert.pem
[root@arongya CA]# ls
cacert.pem  certs  crl  newcerts  private
[root@arongya CA]# touch index.txt && echo 01 > serial
[root@arongya CA]# cat serial 
01

客戶端(nginx)生成密鑰

[root@arongya CA]# cd /usr/local/nginx/
[root@arongya nginx]# mkdir ssl
[root@arongya nginx]# cd ssl
[root@arongya ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus
..+++
....................................................+++
e is 65537 (0x10001)

客戶端生成證書籤署請求

[root@arongya ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn
State or Province Name (full name) []:hb
Locality Name (eg, city) [Default City]:www.yaoxiaorong.com
Organization Name (eg, company) [Default Company Ltd]:www.yaoxiaorong.com
Organizational Unit Name (eg, section) []:www.yaoxiaorong.com
Common Name (eg, your name or your server's hostname) []:www.yaoxiaorong.com
Email Address []:[email protected]

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@arongya ssl]# openssl ca -in ./nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Aug 31 02:56:31 2018 GMT
            Not After : Aug 31 02:56:31 2019 GMT
        Subject:
            countryName               = cn
            stateOrProvinceName       = hb
            organizationName          = www.yaoxiaorong.com
            organizationalUnitName    = www.yaoxiaorong.com
            commonName                = www.yaoxiaorong.com
            emailAddress              = [email protected]
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                D5:16:FA:8F:F5:D8:36:CA:5E:6A:39:91:F9:80:50:A4:B7:06:AD:7A
            X509v3 Authority Key Identifier: 
                keyid:15:9C:26:D9:2A:CC:D7:A7:0A:2A:8D:A1:8F:AB:2F:AB:68:34:27:07

Certificate is to be certified until Aug 31 02:56:31 2019 GMT (365 days)
Sign the certificate? [y/n]:y

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@arongya ssl]# ls
nginx.crt  nginx.csr  nginx.key

編輯配置文件

'取消下面的註釋'
[root@arongya nginx]# vim /usr/local/nginx/conf/nginx.conf
    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  www.yaoxiaorong.com;  '編輯此處'

        ssl_certificate      ../ssl/nginx.crt;   '編輯此處,添加路徑'
        ssl_certificate_key  ../ssl/nginx.key;   '編輯此處,添加路徑'

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

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

}
[root@arongya nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya nginx]# nginx -s reload

在C:\Windows\System32\drivers\etc修改hosts配置文件,將本主機的IP添加進去,還有自己設置的域名。
如圖:
nginx
驗證結果:
nginx

開啓狀態界面


'開啓status'
[root@arongya nginx]# vim conf/nginx.conf
        location /status{
        stub_status on;
        allow 192.168.0.0/16;
        deny all;
            root   html;
            index  index.html index.htm;
        }

[root@arongya nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya nginx]# nginx -s reload

如圖:

nginx

rewrite

[root@arongya nginx]# cd html/
[root@arongya html]# ls
50x.html  index.html
[root@arongya html]# mkdir images
[root@arongya html]# ls
50x.html  images  index.html
[root@arongya html]# cd images/
[root@arongya images]# ls
1.jpg
[root@arongya nginx]# vim conf/nginx.conf
...
        location / {
            root   html;
            index  index.html index.htm;
        }

       location /images {        '//添加從這行開始以下的內容'
            root   html;
            index  index.html;
        }
....
[root@arongya nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya nginx]# nginx -s reload

如圖:
nginx

[root@arongya html]# mv images imgs
[root@arongya nginx]# vim conf/nginx.conf
        location / {
            root   html;
            index  index.html index.htm;
        }

       location /images {
            root   html;
            index  index.html;
            rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;

        }

[root@arongya nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya nginx]# nginx -s reload

如圖:
nginx

[root@arongya nginx]# vim conf/nginx.conf
···
       location /images {
            root   html;
            index  index.html;
            rewrite ^/images/(.*\.jpg)$ http://www.baidu.com redirect;

        }
····
[root@arongya nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya nginx]# nginx -s reload

如圖:
nginx

[root@arongya nginx]# vim conf/nginx.conf
...
       location /images {
            root   html;
            index  index.html;
            rewrite ^/images/(.*\.jpg)$ http://192.168.228.30/index.html redirect;

        }

...
[root@arongya nginx]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@arongya nginx]# nginx -s reload
'直接跳轉到nginx首頁'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章