Nginx相關實戰案例

Nginx相關實戰案例:


Nginx在實際生產中極為重要,先來看一下Nginx配置文件nginx.conf中文詳解

#定義Nginx運行的用戶和用戶組
user www www;
 
#nginx進程數,建議設置為等于CPU總核心數。
worker_processes 8;
 
#全局錯誤日志定義類型,[ debug | info | notice | warn | error | crit ]
error_log /var/log/nginx/error.log info;
 
#進程文件
pid /var/run/nginx.pid;
 
#一個nginx進程打開的最多文件描述符數目,理論值應該是最多打開文件數(系統的值ulimit -n)與nginx進程數相除,但是nginx分配請求并不均勻,所以建議與ulimit -n的值保持一致。
worker_rlimit_nofile 65535;
 
#工作模式與連接數上限
events
{
#參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
use epoll;
#單個進程最大連接數(最大連接數=連接數*進程數)
worker_connections 65535;
}
 
#設定http服務器
http
{
include mime.types; #文件擴展名與文件類型映射表
default_type application/octet-stream; #默認文件類型
#charset utf-8; #默認編碼
server_names_hash_bucket_size 128; #服務器名字的hash表大小
client_header_buffer_size 32k; #上傳文件大小限制
large_client_header_buffers 4 64k; #設定請求緩
client_max_body_size 8m; #設定請求緩
sendfile on; #開啟高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,對于普通應用設為 on,如果用來進行下載等應用磁盤IO重負載應用,可設置為off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。
autoindex on; #開啟目錄列表訪問,合適下載服務器,默認關閉。
tcp_nopush on; #防止網絡阻塞
tcp_nodelay on; #防止網絡阻塞
keepalive_timeout 120; #長連接超時時間,單位是秒
 
#FastCGI相關參數是為了改善網站的性能:減少資源占用,提高訪問速度。下面參數看字面意思都能理解。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
 
#gzip模塊設置
gzip on; #開啟gzip壓縮輸出
gzip_min_length 1k; #最小壓縮文件大小
gzip_buffers 4 16k; #壓縮緩沖區
gzip_http_version 1.0; #壓縮版本(默認1.1,前端如果是squid2.5請使用1.0)
gzip_comp_level 2; #壓縮等級
gzip_types text/plain application/x-javascript text/css application/xml;
#壓縮類型,默認就已經包含text/html,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
gzip_vary on;
#limit_zone crawler $binary_remote_addr 10m; #開啟限制IP連接數的時候需要使用
 
upstream blog.ha97.com {
#upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的幾率越大。
server 192.168.80.121:80 weight=3;
server 192.168.80.122:80 weight=2;
server 192.168.80.123:80 weight=3;
}
 
#虛擬主機的配置
server
{
#監聽端口
listen 80;
#域名可以有多個,用空格隔開
server_name www.ha97.com ha97.com;
index index.html index.htm index.php;
root /data/www/ha97;
location ~ .*\.(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
#圖片緩存時間設置
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 10d;
}
#JS和CSS緩存時間設置
location ~ .*\.(js|css)?$
{
expires 1h;
}
#日志格式設定
log_format access '$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/ha97access.log access;
 
#對 "/" 啟用反向代理
location / {
proxy_pass http://127.0.0.1:88;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
#后端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#以下是一些反向代理的配置,可選。
proxy_set_header Host $host;
client_max_body_size 10m; #允許客戶端請求的最大單文件字節數
client_body_buffer_size 128k; #緩沖區代理緩沖用戶端請求的最大字節數,
proxy_connect_timeout 90; #nginx跟后端服務器連接超時時間(代理連接超時)
proxy_send_timeout 90; #后端服務器數據回傳時間(代理發送超時)
proxy_read_timeout 90; #連接成功后,后端服務器響應時間(代理接收超時)
proxy_buffer_size 4k; #設置代理服務器(nginx)保存用戶頭信息的緩沖區大小
proxy_buffers 4 32k; #proxy_buffers緩沖區,網頁平均在32k以下的設置
proxy_busy_buffers_size 64k; #高負荷下緩沖大?。╬roxy_buffers*2)
proxy_temp_file_write_size 64k;
#設定緩存文件夾大小,大于這個值,將從upstream服務器傳
}
 
#設定查看Nginx狀態的地址
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
#htpasswd文件的內容可以用apache提供的htpasswd工具來產生。
}
 
#本地動靜分離反向代理配置
#所有jsp的頁面均交由tomcat或resin處理
location ~ .(jsp|jspx|do)?$ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
#所有靜態文件由nginx直接讀取不經過tomcat或resin
location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
{ expires 15d; }
location ~ .*.(js|css)?$
{ expires 1h; }
}
}


一、 1.$remote_addr $http_x_forwarded_for 用以記錄客戶端的ip地址;

2.$remote_user :用來記錄客戶端用戶名稱;

3.$time_local : 用來記錄訪問時間與時區;

4.$request : 用來記錄請求的urlhttp協議;

5.$status : 用來記錄請求狀態;成功是200

6.$body_bytes_s ent :記錄發送給客戶端文件主體內容大??;

7.$http_referer :用來記錄從那個頁面鏈接訪問過來的;

8.$http_user_agent :記錄客戶端瀏覽器的相關信息;

二、 驚群現象:一個網路連接到來,多個睡眠的進程被同時叫醒,但只有一個進程能獲得鏈接,這樣會影響系統性能。

三、 每個指令必須有分號結束。

#user administrator administrators;  #配置用戶或者組,默認為nobody nobody。
#worker_processes 2;  #允許生成的進程數,默認為1
#pid /nginx/pid/nginx.pid;   #指定nginx進程運行文件存放地址
error_log log/error.log debug;  #制定日志路徑,級別。這個設置可以放入全局塊,http塊,server塊,級別以此為:debug|info|notice|warn|error|crit|alert|emerg
#工作模式及連接數上限
events {
    accept_mutex on;   #設置網路連接序列化,防止驚群現象發生,默認為on
    multi_accept on;  #設置一個進程是否同時接受多個網絡連接,默認為off
    #use epoll;      #事件驅動模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大連接數,默認為512
}
#設定http服務器,利用它的反向代理功能提供負載均衡支持
http {
    include       mime.types;   #文件擴展名與文件類型映射表
    default_type  application/octet-stream; #默認文件類型,默認為text/plain
    #access_log off; #取消服務日志    
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定義格式
    access_log log/access.log myFormat;  #combined為日志格式的默認值
    sendfile on;   #允許sendfile方式傳輸文件,默認為off,可以在http塊,server塊,location塊。
    sendfile_max_chunk 100k;  #每個進程每次調用傳輸數量不能大于設定的值,默認為0,即不設上限。
    keepalive_timeout 65;  #連接超時時間,默認為75s,可以在http,server,location塊。
 
#設定負載均衡的服務器列表
    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #熱備
    }
    error_page 404 https://www.baidu.com; #錯誤頁
    server {
        keepalive_requests 120; #單連接請求上限次數。
        listen       4545;   #監聽端口
        server_name  127.0.0.1;   #監聽地址       
        location  ~*^.+$ {       #請求的url過濾,正則匹配,~為區分大小寫,~*為不區分大小寫。
           #root path;  #根目錄
           #index vv.txt;  #設置默認頁
           proxy_pass  http://mysvr;  #請求轉向mysvr 定義的服務器列表
           deny 127.0.0.1;  #拒絕的ip
           allow 172.18.5.54; #允許的ip           
        }
    }
}

負載均衡配置


網站在實際運營過程中,多半都是有多臺服務器運行著同樣的app,這時需要使用負載均衡來分流。nginx也可以實現簡單的負載均衡功能。

nginx.conf 配置如下:

#設定http服務器,利用它的反向代理功能提供負載均衡支持
http {
     #設定mime類型,類型由mime.type文件定義
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    #設定日志格式
    access_log    /var/log/nginx/access.log;
    #省略上文有的一些配置節點
    #。。。。。。。。。。
    #設定負載均衡的服務器列表
     upstream mysvr {
    #weigth參數表示權值,權值越高被分配到的幾率越大
    server 192.168.8.1x:3128 weight=5;#本機上的Squid開啟3128端口
    server 192.168.8.2x:80  weight=1;
    server 192.168.8.3x:80  weight=6;
    }
   upstream mysvr2 {
    #weigth參數表示權值,權值越高被分配到的幾率越大
    server 192.168.8.x:80  weight=1;
    server 192.168.8.x:80  weight=6;
    }
   #第一個虛擬服務器
   server {
    #偵聽192.168.8.x的80端口
        listen       80;
        server_name  192.168.8.x;
      #對aspx后綴的進行負載均衡請求
    location ~ .*\.aspx$ {
         root   /root;      #定義服務器的默認網站根目錄位置
          index index.php index.html index.htm;   #定義首頁索引文件的名稱
          proxy_pass  http://mysvr ;#請求轉向mysvr 定義的服務器列表
          #以下是一些反向代理的配置可刪除.
          proxy_redirect off;
          #后端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          client_max_body_size 10m;    #允許客戶端請求的最大單文件字節數
          client_body_buffer_size 128k;  #緩沖區代理緩沖用戶端請求的最大字節數,
          proxy_connect_timeout 90;  #nginx跟后端服務器連接超時時間(代理連接超時)
          proxy_send_timeout 90;       #后端服務器數據回傳時間(代理發送超時)
          proxy_read_timeout 90;       #連接成功后,后端服務器響應時間(代理接收超時)
          proxy_buffer_size 4k;        #設置代理服務器(nginx)保存用戶頭信息的緩沖區大小
          proxy_buffers 4 32k;         #proxy_buffers緩沖區,網頁平均在32k以下的話,這樣設置
          proxy_busy_buffers_size 64k;    #高負荷下緩沖大?。╬roxy_buffers*2)
          proxy_temp_file_write_size 64k;  #設定緩存文件夾大小,大于這個值,將從upstream服務器傳
       }
     }
}

https反向代理配置


一些對安全性要求比較高的站點,可能會使用 HTTPS(一種使用ssl通信標準的安全HTTP協議)。

使用 nginx 配置 https 需要知道幾點:

HTTPS 的固定端口號是443,不同HTTP80端口

SSL 標準需要引入安全證書,所以在nginx.conf中你需要指定證書和它對應的key

其他和 http 反向代理基本一樣,只是在 Server 部分配置有些不同。

#HTTP服務器
server {
#監聽443端口。443為知名端口號,主要用于HTTPS協議
listen       443 ssl;
 
#定義使用www.xx.com訪問
server_name  www.helloworld.com;
#ssl證書文件位置(常見證書文件格式為:crt/pem)
ssl_certificate      cert.pem;
#ssl證書key位置
ssl_certificate_key  cert.key;
 
#ssl配置參數(選擇性配置)
ssl_session_cache    shared:SSL:1m;
ssl_session_timeout  5m;
#數字簽名,此處使用MD5
ssl_ciphers  HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers  on;
location / {
root   /root;
index  index.html index.htm;
}
}

靜態站點配置


有時候,我們需要配置靜態站點(html 文件和一堆靜態資源)。

舉例來說:如果所有的靜態資源都放在了 /app/dist 目錄下,我們只需要在 nginx.conf 中指定首頁以及這個站點的 host 即可。

配置如下:

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
gzip on;
    gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/javascript image/jpeg image/gif image/png;
    gzip_vary on;
 
    server {
        listen       80;
        server_name  static.zp.cn;
 
        location / {
            root /app/dist;
            index index.html;
            #轉發任何請求到 index.html
        }
    }
}
然后,添加 HOST:
127.0.0.1 static.zp.cn
此時,在本地瀏覽器訪問 static.zp.cn ,就可以訪問靜態站點了。

http反向代理配置


#運行用戶
#user somebody;
 
#啟動進程,通常設置成和cpu的數量相等
worker_processes  1;
 
#全局錯誤日志
error_log  D:/Tools/nginx-1.10.1/logs/error.log;
error_log  D:/Tools/nginx-1.10.1/logs/notice.log  notice;
error_log  D:/Tools/nginx-1.10.1/logs/info.log  info;
 
#PID文件,記錄當前啟動的nginx的進程ID
pid        D:/Tools/nginx-1.10.1/logs/nginx.pid;
 
#工作模式及連接數上限
events {
    worker_connections 1024;    #單個后臺worker process進程的最大并發鏈接數
}
 
#設定http服務器,利用它的反向代理功能提供負載均衡支持
http {
    #設定mime類型(郵件支持類型),類型由mime.types文件定義
    include       D:/Tools/nginx-1.10.1/conf/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    D:/Tools/nginx-1.10.1/logs/access.log main;
    rewrite_log     on;
    
    #sendfile 指令指定 nginx 是否調用 sendfile 函數(zero copy 方式)來輸出文件,對于普通應用,
    #必須設為 on,如果用來進行下載等應用磁盤IO重負載應用,可設置為 off,以平衡磁盤與網絡I/O處理速度,降低系統的uptime.
    sendfile        on;
    #tcp_nopush     on;
 
    #連接超時時間
    keepalive_timeout  120;
    tcp_nodelay        on;
    
    #gzip壓縮開關
    #gzip  on;
 
#設定實際的服務器列表
    upstream zp_server1{
        server 127.0.0.1:8089;
    }
 
    #HTTP服務器
    server {
        #監聽80端口,80端口是知名端口號,用于HTTP協議
        listen       80;
        
        #定義使用www.xx.com訪問
        server_name  www.helloworld.com;
        
        #首頁
        index index.html
        
        #指向webapp的目錄
        root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp;
        
        #編碼格式
        charset utf-8;
        
#代理配置參數
        proxy_connect_timeout 180;
        proxy_send_timeout 180;
        proxy_read_timeout 180;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarder-For $remote_addr;
 
        #反向代理的路徑(和upstream綁定),location 后面設置映射的路徑
        location / {
            proxy_pass http://zp_server1;
        }
 
        #靜態文件,nginx自己處理
        location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp\views;
            #過期30天,靜態文件不怎么更新,過期可以設大一點,如果頻繁更新,則可以設置得小一點。
            expires 30d;
        }
    
#設定查看Nginx狀態的地址
        location /NginxStatus {
            stub_status           on;
            access_log            on;
            auth_basic            "NginxStatus";
            auth_basic_user_file  conf/htpasswd;
        }
    
        #禁止訪問 .htxxx 文件
        location ~ /\.ht {
            deny all;
        }
        
        #錯誤處理頁面(可選擇性配置)
        #error_page   404              /404.html;
        #error_page   500 502 503 504  /50x.html;
        #location = /50x.html {
        #    root   html;
        #}
    }
}
1.啟動 webapp,注意啟動綁定的端口要和nginx中的 upstream 設置的端口保持一致。
2.更改 host:在 C:\Windows\System32\drivers\etc 目錄下的host文件中添加一條 DNS 記錄
127.0.0.1 www.helloworld.com
3.啟動前文中 startup.bat 的命令
4.在瀏覽器中訪問 www.helloworld.com,已經可以訪問了。

 

 

 

參考文檔:

http://tool.oschina.net/apidocs/apidoc?api=nginx-zh

原創文章,作者:Linux.rookie,如若轉載,請注明出處:http://www.www58058.com/78236

(0)
Linux.rookieLinux.rookie
上一篇 2017-06-19
下一篇 2017-06-19

相關推薦

  • Linux三劍客awk命令

    1 .awk是一個強大的文本分析工具,相對于grep的查找,sed的編輯,awk在其對數據分析并生成報告時,顯得尤為強大。簡單來說awk就是把文件逐行的讀入,以空格為默認分隔符將每行切片,切開的部分再進行各種分析處理。 awk有3個不同版本: awk、nawk和gawk,未作特別說明,一般指gawk,gawk 是 AWK 的 GNU 版本。 awk其名稱得自…

    2017-09-08
  • 0803權限管理作業練習

    0803權限管理作業練習 題目:創建組sales,gid 3000,passwd :centos,sales 的組管理員admins:user2 將用戶user1,user2,user3加入到sales輔助組 希望user1創建新文件默認的所屬組為sales user2將用戶user3從sales組移除   答案:   &nbs…

    Linux干貨 2016-08-05
  • 【N25第一周作業】Linux基礎

    題目:   1、描述計算機的組成及其功能。   2、按系列羅列Linux的發行版,并描述不同發行版之間的聯系與區別。   3、描述Linux的哲學思想,并按照自己的理解對其進行解釋性描述。   4、說明Linux系統上命令的使用格式;詳細介紹ifconfig、echo、tty、startx、export、pwd、his…

    Linux干貨 2016-12-03
  • 文本三劍客 grep sed awk

    模式,選項。常用用法。

    2017-12-03
  • M22 Centos6上編譯安裝httpd2.4并實現HTTPS瀏覽

    隨著網絡技術的發展,人們對信息安全越來越重視,傳統的http瀏覽互聯網的方式由于未經加密,其安全性廣為人們詬病,https協議作為加密的互聯網解決方案解決了這一問題。下面我就簡要說明下如何實現通過https發布web頁面的。   實驗目的: 模擬Centos6上安裝httpd2.4,并實現https加密訪問主頁 實驗器材: Centos6.8虛擬機…

    Linux干貨 2017-04-20
欧美性久久久久