nginx(配置詳細說明)

 

一 Nginx簡介javascript

   Nginx是一款開源代碼的高性能HTTP服務器和反向代理服務器,同時支持IMAP/POP3/SMTP代理服務php

   1.Nginx工做原理css

       Nginx由內核和模塊組成,完成工做是經過查找配置文件將客戶端請求映射到一個location block(location是用於URL匹配的命令),location配置的命令會啓動不一樣模塊完成工做。html

       Nginx模塊分爲核心模塊,基礎模塊和第三方模塊。前端

           核心模塊:HTTP模塊、EVENT模塊(事件)、MAIL模塊。java

           基礎模塊:HTTP Access模塊、HTTP FastCGI模塊、HTTP Proxy模塊、HTTP Rewrite模塊。node

           第三方模塊:HTTP Upstream Request Hash模塊、Notice模塊、HTTP Access Key模塊。nginx

   

   2.性能優點web

       web服務器,處理靜態文件、索引文件以及自動索引效率高。算法

       代理服務器,快速高效反向代理,提高網站性能。

       負載均衡器,內部支持Rails和PHP,也可支持HTTP代理服務器,對外進行服務。同時支持簡單容錯和利用算法進行負載均衡。

       性能方面,Nginx專門爲性能設計,實現注重效率。採用Poll模型,能夠支持更多的併發鏈接,並在大併發時佔用很低內存。

       穩定性方面,採用分階段資源分配技術,使CPU資源佔用率低。

       高可用性方面,支持熱備,啓動迅速。

二 Nginx編譯安裝,配置文件詳解

   1.Nginx安裝

 
  1. #安裝部署nginx所用到的安裝工具和相關庫
  2. #默認安裝的http_rewrite_module(使用正則對請求重寫)需pcre庫
  3. #默認安裝的httP_gzip_module(Gzip壓縮)需zlib庫
  4. #安裝http_ssl_module(HTTPS/SLL)需openssl庫
  5. yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
  6. #下載nginx源碼包,並解壓
  7. wget http://nginx.org/download/nginx-1.10.3.tar.gz
  8. tar -zxvf nginx-1.10.3.tar.gz
  9. cd nginx-1.10.3
  10. #設置參數 參數具體參考《Nginx編譯參數》
  11. ./configure \
  12. --prefix=/usr/local/nginx \
  13. --with-http_ssl_module
  14. #編譯並安裝 
  15. make && make install

   2.Nginx配置文件(/usr/local/nginx/conf/nginx.conf)

   

   配置文件主要由四部分組成:main(全區設置),server(主機配置),upstream(負載均衡服務器設置),和location(URL匹配特定位置設置)。

   1)全局變量

 
  1. #Nginx的worker進程運行用戶以及用戶組
  2. #user nobody nobody;
  3. #Nginx開啓的進程數
  4. worker_processes 1;
  5. #worker_processes auto;
  6. #如下參數指定了哪一個cpu分配給哪一個進程,通常來講不用特殊指定。若是必定要設的話,用0和1指定分配方式.
  7. #這樣設就是給1-4個進程分配單獨的核來運行,出現第5個進程是就是隨機分配了。eg:
  8. #worker_processes 4 #4核CPU
  9. #worker_cpu_affinity 0001 0010 0100 1000
  10.  
  11. #定義全局錯誤日誌定義類型,[debug|info|notice|warn|crit]
  12. #error_log logs/error.log info;
  13. #指定進程ID存儲文件位置
  14. #pid logs/nginx.pid;
  15. #一個nginx進程打開的最多文件描述符數目,理論值應該是最多打開文件數(ulimit -n)與nginx進程數相除,可是nginx分配請求並非那麼均勻,因此最好與ulimit -n的值保持一致。
  16. #vim /etc/security/limits.conf
  17. # * soft nproc 65535
  18. # * hard nproc 65535
  19. # * soft nofile 65535
  20. # * hard nofile 65535
  21. worker_rlimit_nofile 65535;

    2)事件配置

 
  1. events {
  2. #use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,若是跑在FreeBSD上面,就用kqueue模型。
  3. use epoll;
  4. #每一個進程能夠處理的最大鏈接數,理論上每臺nginx服務器的最大鏈接數爲worker_processes*worker_connections。理論值:worker_rlimit_nofile/worker_processes
  5. #注意:最大客戶數也由系統的可用socket鏈接數限制(~ 64K),因此設置不切實際的高沒什麼好處
  6. worker_connections 65535;
  7. #worker工做方式:串行(必定程度下降負載,但服務器吞吐量大時,關閉使用並行方式)
  8. #multi_accept on;
  9. }

   3)http參數

 
  1. #文件擴展名與文件類型映射表
  2. include mime.types;
  3. #默認文件類型
  4. default_type application/octet-stream;
  5.  
  6. #日誌相關定義
  7. #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  8. # '$status $body_bytes_sent "$http_referer" '
  9. # '"$http_user_agent" "$http_x_forwarded_for"';
  10. #定義日誌的格式。後面定義要輸出的內容。
  11. #1.$remote_addr 與$http_x_forwarded_for 用以記錄客戶端的ip地址;
  12. #2.$remote_user :用來記錄客戶端用戶名稱;
  13. #3.$time_local :用來記錄訪問時間與時區;
  14. #4.$request :用來記錄請求的url與http協議;
  15. #5.$status :用來記錄請求狀態;
  16. #6.$body_bytes_sent :記錄發送給客戶端文件主體內容大小;
  17. #7.$http_referer :用來記錄從那個頁面連接訪問過來的;
  18. #8.$http_user_agent :記錄客戶端瀏覽器的相關信息
  19. #鏈接日誌的路徑,指定的日誌格式放在最後。
  20. #access_log logs/access.log main;
  21. #只記錄更爲嚴重的錯誤日誌,減小IO壓力
  22. error_log logs/error.log crit;
  23. #關閉日誌
  24. #access_log off;
  25.  
  26. #默認編碼
  27. #charset utf-8;
  28. #服務器名字的hash表大小
  29. server_names_hash_bucket_size 128;
  30. #客戶端請求單個文件的最大字節數
  31. client_max_body_size 8m;
  32. #指定來自客戶端請求頭的hearerbuffer大小
  33. client_header_buffer_size 32k;
  34. #指定客戶端請求中較大的消息頭的緩存最大數量和大小。
  35. large_client_header_buffers 4 64k;
  36. #開啓高效傳輸模式。
  37. sendfile on;
  38. #防止網絡阻塞
  39. tcp_nopush on;
  40. tcp_nodelay on;    
  41. #客戶端鏈接超時時間,單位是秒
  42. keepalive_timeout 60;
  43.    #客戶端請求頭讀取超時時間
  44.    client_header_timeout 10;
  45.    #設置客戶端請求主體讀取超時時間
  46.    client_body_timeout 10;
  47.    #響應客戶端超時時間
  48.   send_timeout 10;
  49.  
  50. #FastCGI相關參數是爲了改善網站的性能:減小資源佔用,提升訪問速度。
  51. fastcgi_connect_timeout 300;
  52. fastcgi_send_timeout 300;
  53. fastcgi_read_timeout 300;
  54. fastcgi_buffer_size 64k;
  55. fastcgi_buffers 4 64k;
  56. fastcgi_busy_buffers_size 128k;
  57. fastcgi_temp_file_write_size 128k;
  58.  
  59. #gzip模塊設置
  60. #開啓gzip壓縮輸出
  61. gzip on;
  62. #最小壓縮文件大小
  63. gzip_min_length 1k;
  64. #壓縮緩衝區
  65. gzip_buffers 4 16k;
  66. #壓縮版本(默認1.1,前端若是是squid2.5請使用1.0)
  67. gzip_http_version 1.0;
  68. #壓縮等級 1-9 等級越高,壓縮效果越好,節約寬帶,但CPU消耗大
  69. gzip_comp_level 2;
  70. #壓縮類型,默認就已經包含text/html,因此下面就不用再寫了,寫上去也不會有問題,可是會有一個warn。
  71. gzip_types text/plain application/x-javascript text/css application/xml;
  72.    #前端緩存服務器緩存通過壓縮的頁面
  73.  gzip_vary on;

    4)虛擬主機基本設置

 
  1. #虛擬主機定義
  2. server {
  3.        #監聽端口
  4. listen 80;
  5.        #訪問域名
  6. server_name localhost;
  7.        #編碼格式,若網頁格式與此不一樣,將被自動轉碼
  8. #charset koi8-r;
  9.        #虛擬主機訪問日誌定義
  10. #access_log logs/host.access.log main;
  11.        #對URL進行匹配
  12. location / {
  13.            #訪問路徑,可相對也可絕對路徑
  14. root html;
  15.            #首頁文件。如下按順序匹配
  16. index index.html index.htm;
  17. }
  18.  
  19. #錯誤信息返回頁面
  20. #error_page 404 /404.html;
  21. # redirect server error pages to the static page /50x.html
  22. #
  23. error_page 500 502 503 504 /50x.html;
  24. location = /50x.html {
  25. root html;
  26. }
  27.  
  28. #訪問URL以.php結尾則自動轉交給127.0.0.1
  29. # proxy the PHP scripts to Apache listening on 127.0.0.1:80
  30. #
  31. #location ~ \.php$ {
  32. # proxy_pass http://127.0.0.1;
  33. #}
  34. #php腳本請求所有轉發給FastCGI處理
  35. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  36. #
  37. #location ~ \.php$ {
  38. # root html;
  39. # fastcgi_pass 127.0.0.1:9000;
  40. # fastcgi_index index.php;
  41. # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  42. # include fastcgi_params;
  43. #}
  44.  
  45. #禁止訪問.ht頁面 (需ngx_http_access_module模塊)
  46. # deny access to .htaccess files, if Apache's document root
  47. # concurs with nginx's one
  48. #
  49. #location ~ /\.ht {
  50. # deny all;
  51. #}
  52. }
  53. #HTTPS虛擬主機定義
  54. # HTTPS server
  55. #
  56. #server {
  57. # listen 443 ssl;
  58. # server_name localhost;
  59. # ssl_certificate cert.pem;
  60. # ssl_certificate_key cert.key;
  61. # ssl_session_cache shared:SSL:1m;
  62. # ssl_session_timeout 5m;
  63. # ssl_ciphers HIGH:!aNULL:!MD5;
  64. # ssl_prefer_server_ciphers on;
  65. # location / {
  66. # root html;
  67. # index index.html index.htm;
  68. # }
  69. #}

    5)Nignx狀態監控

 
  1. #Nginx運行狀態,StubStatus模塊獲取Nginx自啓動的工做狀態(編譯時要開啓對應功能)
  2. #location /NginxStatus {
  3. #    #啓用StubStatus的工做訪問狀態    
  4. #    stub_status    on;
  5.        #    #指定StubStaus模塊的訪問日誌文件
  6. #    access_log    logs/Nginxstatus.log;
  7.     #    #Nginx認證機制(需Apache的htpasswd命令生成)
  8. #    #auth_basic    "NginxStatus";
  9.     #    #用來認證的密碼文件
  10. #    #auth_basic_user_file    ../htpasswd;
  11. #}
  12. 訪問:http://IP/NginxStatus(測試就不加密碼驗證相關)

    6)反向代理

 
  1. #如下配置追加在HTTP的全局變量中
  2.  
  3. #nginx跟後端服務器鏈接超時時間(代理鏈接超時)
  4. proxy_connect_timeout 5;
  5. #後端服務器數據回傳時間(代理髮送超時)
  6. proxy_send_timeout 5;
  7. #鏈接成功後,後端服務器響應時間(代理接收超時)
  8. proxy_read_timeout 60;
  9. #設置代理服務器(nginx)保存用戶頭信息的緩衝區大小
  10. proxy_buffer_size 16k;
  11. #proxy_buffers緩衝區,網頁平均在32k如下的話,這樣設置
  12. proxy_buffers 4 32k;
  13. #高負荷下緩衝大小(proxy_buffers*2)
  14. proxy_busy_buffers_size 64k;
  15. #設定緩存文件夾大小,大於這個值,將從upstream服務器傳
  16. proxy_temp_file_write_size 64k;
  17. #反向代理緩存目錄
  18. proxy_cache_path /data/proxy/cache levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=1g;
  19. #levels=1:2 設置目錄深度,第一層目錄是1個字符,第2層是2個字符
  20. #keys_zone:設置web緩存名稱和內存緩存空間大小
  21. #inactive:自動清除緩存文件時間。
  22. #max_size:硬盤空間最大可以使用值。
  23. #指定臨時緩存文件的存儲路徑(路徑需和上面路徑在同一分區)
  24. proxy_temp_path /data/proxy/temp
  25.  
  26. #服務配置
  27. server {
  28. #偵聽的80端口
  29. listen 80;
  30. server_name localhost;
  31. location / {
  32.        #反向代理緩存設置命令(proxy_cache zone|off,默認關閉因此要設置)
  33.        proxy_cache cache_one;
  34.        #對不一樣的狀態碼緩存不一樣時間
  35.        proxy_cache_valid 200 304 12h;
  36.        #設置以什麼樣參數獲取緩存文件名
  37.        proxy_cache_key $host$uri$is_args$args;
  38. #後7端的Web服務器能夠經過X-Forwarded-For獲取用戶真實IP
  39. proxy_set_header Host $host;
  40. proxy_set_header X-Real-IP $remote_addr;
  41. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  42. #代理設置
  43. proxy_pass http://IP;
  44.        #文件過時時間控制
  45. expires    1d;
  46. }
  47.    #配置手動清楚緩存(實現此功能需第三方模塊 ngx_cache_purge)
  48.    #http://www.123.com/2017/0316/17.html訪問
  49. #http://www.123.com/purge/2017/0316/17.html清楚URL緩存
  50. location ~ /purge(/.*) {
  51. allow    127.0.0.1;
  52. deny    all;
  53. proxy_cache_purge    cache_one    $host$1$is_args$args;
  54. }
  55. #設置擴展名以.jsp、.php、.jspx結尾的動態應用程序不作緩存
  56.    location ~.*\.(jsp|php|jspx)?$ {
  57. proxy_set_header Host $host;
  58. proxy_set_header X-Real-IP $remote_addr;
  59. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  60. proxy_pass http://http://IP;
  61. }

    7)負載均衡

 
  1. #負載均衡服務器池
  2. upstream my_server_pool {
  3.    #調度算法
  4.    #1.輪循(默認)(weight輪循權值)
  5.    #2.ip_hash:根據每一個請求訪問IP的hash結果分配。(會話保持)
  6.    #3.fair:根據後端服務器響應時間最短請求。(upstream_fair模塊)
  7.    #4.url_hash:根據訪問的url的hash結果分配。(需hash軟件包)
  8.    #參數:
  9.    #down:表示不參與負載均衡
  10.    #backup:備份服務器
  11.    #max_fails:容許最大請求錯誤次數
  12.    #fail_timeout:請求失敗後暫停服務時間。
  13. server 192.168.1.109:80 weight=1 max_fails=2 fail_timeout=30;
  14. server 192.168.1.108:80 weight=2 max_fails=2 fail_timeout=30;
  15. }
  16. #負載均衡調用
  17. server {
  18. ...
  19.    location / {
  20. proxy_pass http://my_server_pool;
  21. }
  22. }

    8)URL重寫

 
  1. #根據不一樣的瀏覽器URL重寫
  2. if($http_user_agent ~ Firefox){
  3. rewrite ^(.*)$ /firefox/$1 break;
  4. }
  5. if($http_user_agent ~ MSIE){
  6. rewrite ^(.*)$ /msie/$1 break;
  7. }
  8.  
  9. #實現域名跳轉
  10. location / {
  11. rewrite ^/(.*)$ https://web8.example.com$1 permanent;
  12. }

    9)IP限制

 
  1. #限制IP訪問
  2. location / {
  3. deny 192.168.0.2;
  4. allow 192.168.0.0/24;
  5. allow 192.168.1.1;
  6. deny all;
  7. }

    10)Nginx相關命令

 
  1. #啓動nginx
  2. nginx
  3. #關閉nginx
  4. nginx -s stop
  5. #平滑重啓
  6. kill -HUP `cat /usr/local/nginx/logs/nginx.pid`

    11)Nginx啓動腳本

 
  1. #!/bin/bash
  2. #chkconfig: 2345 80 90 #description:auto_run
  3. PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
  4. export PATH
  5.  
  6. # Check if user is root
  7. if [ $(id -u) != "0" ]; then
  8. echo "Error: You must be root to run this script!\n"
  9. exit 1
  10. fi
  11.  
  12. NGINXDAEMON=/usr/local/nginx/sbin/nginx
  13. PIDFILE=/usr/local/nginx/logs/nginx.pid
  14.  
  15. function_start()
  16. {
  17. echo -en "\033[32;49;1mStarting nginx......\n"
  18. echo -en "\033[39;49;0m"
  19. if [ -f $PIDFILE ]; then
  20. printf "Nginx is runing!\n"
  21. exit 1
  22. else
  23. $NGINXDAEMON
  24. printf "Nginx is the successful start!\n"
  25. fi
  26. }
  27.  
  28. function_stop()
  29. {
  30. echo -en "\033[32;49;1mStoping nginx......\n"
  31. echo -en "\033[39;49;0m"
  32. if [ -f $PIDFILE ]; then
  33. kill `cat $PIDFILE`
  34. printf "Nginx program is stoped\n"
  35. else
  36. printf "Nginx program is not runing!\n"
  37. fi
  38. }
  39.  
  40. function_reload()
  41. {
  42. echo -en "\033[32;49;1mReload nginx......\n"
  43. echo -en "\033[39;49;0m"
  44. function_stop function_start
  45. }
  46.  
  47. function_restart()
  48. {
  49. echo -en "\033[32;49;1mRestart nginx......\n"
  50. echo -en "\033[39;49;0m"
  51. printf "Reload Nginx configure...\n"
  52. $NGINXDAEMON -t
  53. kill -HUP `cat $PIDFILE`
  54. printf "Nginx program is reloding!\n"
  55. }
  56.  
  57. function_kill()
  58. {
  59. killall nginx
  60. }
  61.  
  62. function_status()
  63. {
  64. if ! ps -ef|grep -v grep|grep 'nginx:' > /dev/null 2>&1
  65. then
  66. printf "Nginx is down!!!\n"
  67. else
  68. printf "Nginx is running now!\n"
  69. fi
  70. }
  71.  
  72. if [ "$1" = "start" ]; then
  73. function_start
  74. elif [ "$1" = "stop" ]; then
  75. function_stop
  76. elif [ "$1" = "reload" ]; then
  77. function_reload
  78. elif [ "$1" = "restart" ]; then
  79. function_restart
  80. elif [ "$1" = "kill" ]; then
  81. function_kill
  82. elif [ "$1" = "status" ]; then
  83. function_status
  84. else
  85. echo -en "\033[32;49;1m Usage: nginx {start|stop|reload|restart|kill|status}\n"
  86. echo -en "\033[39;49;0m"
  87. fi
相關文章
相關標籤/搜索