天天看點

Nginx 配置檔案解析

(1)全局配置
#Nginx的worker程序運作使用者以及使用者組
user  nginx nginx;
#Nginx開啟的程序數, 建議設定為CPU總核心數
worker_processes  1;
#worker_processes auto; 
#以下參數指定了哪個cpu配置設定給哪個程序,一般來說不用特殊指定。如果一定要設的話,用0和1指定配置設定方式.
#這樣設就是給1-4個程序配置設定單獨的核來運作,出現第5個程序是就是随機配置設定了。eg:
#worker_processes 4     #4核CPU 
#worker_cpu_affinity 0001 0010 0100 1000

#定義全局錯誤日志定義類型,[debug|info|notice|warn|crit]
error_log  logs/error.log  info;
#指定程序ID存儲檔案位置
pid        logs/nginx.pid;
#一個nginx程序打開的最多檔案描述符數目,理論值應該是最多打開檔案數(ulimit -n)與nginx程序數相除,但是nginx配置設定請求并不是那麼均勻,是以最好與ulimit -n的值保持一緻。
#vim /etc/security/limits.conf
#  *                soft    nproc          65535
#  *                hard    nproc          65535
#  *                soft    nofile         65535
#  *                hard    nofile         65535
worker_rlimit_nofile 65535;

(2)事件配置
events {
    #use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本核心中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。Solaris中使用/dev/poll,windows中使用icop
    use epoll;
    #每個程序可以處理的最大連接配接數,理論上每台nginx伺服器的最大連接配接數為worker_processes*worker_connections。理論值:worker_rlimit_nofile/worker_processes
    #注意:最大客戶數也由系統的可用socket連接配接數限制(~ 64K),是以設定不切實際的高沒什麼好處
    worker_connections  65535;    
    #worker工作方式:串行(一定程度降低負載,但伺服器吞吐量大時,關閉使用并行方式)
    #multi_accept on; 
}

(3)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"';
    #定義日志的格式。後面定義要輸出的内容。
    #1.$remote_addr 與$http_x_forwarded_for 用以記錄用戶端的ip位址;
    #2.$remote_user :用來記錄用戶端使用者名稱;
    #3.$time_local :用來記錄通路時間與時區;
    #4.$request  :用來記錄請求的url與http協定;
    #5.$status :用來記錄請求狀态; 
    #6.$body_bytes_sent :記錄發送給用戶端檔案主體内容大小;
    #7.$http_referer :用來記錄從那個頁面連結通路過來的;
    #8.$http_user_agent :記錄用戶端浏覽器的相關資訊
    #連接配接日志的路徑,指定的日志格式放在最後。
    access_log  logs/access.log  main;
    #隻記錄更為嚴重的錯誤日志,減少IO壓力
    error_log logs/error.log crit;
    #關閉日志
    #access_log  off;

    #預設編碼
    #charset utf-8;
    #伺服器名字的hash表大小
    server_names_hash_bucket_size 128;
    #用戶端請求單個檔案的最大位元組數
    client_max_body_size 8m;
    #指定來自用戶端請求頭的hearerbuffer大小
    client_header_buffer_size 32k;
    #指定用戶端請求中較大的消息頭的緩存最大數量和大小。
    large_client_header_buffers 4 64k;
    #開啟高效傳輸模式。
    sendfile        on;
    #防止網絡阻塞,作用是激活或禁用Linux上的TCP_CORK socket選項,此選項隻有開啟sendfile才生效,激活這個,tcp_nopush參數可以允許把http response header和檔案的開始部分放在一個檔案裡釋出,其積極的作用是減少網絡封包段的數量。
    tcp_nopush on;
    #用于激活tcp_nopush,提高I/O性能。預設情況下當發送資料時,核心不會馬上發送而是會等待更多位元組組成一個資料包,這樣可以提高I/O,當在每次發送很少位元組的業務場景下,使用tcp_nodelay功能,等待的時間會比較長。
    tcp_nodelay on;    
    #用戶端連接配接逾時時間,機關是秒
    keepalive_timeout 60;
    #用戶端請求頭讀取逾時時間;作用:讀取用戶端請求頭資料的時間逾時,用戶端還沒有發送完整的header資料,伺服器放回408,防止用戶端利用http協定進行攻擊。
    client_header_timeout 10;
    #設定用戶端請求主體讀取逾時時間,作用同上。這個逾時僅僅是兩次成功的讀取操作之間的一個逾時,并非是請求整個主體資料的逾時。預設值60秒
    client_body_timeout 10;
    #響應用戶端逾時時間,這個逾時僅為兩次成功握手後的逾時時間,不是整個相應資料的逾時時間,如果超過這個時間,用戶端沒有接收任何資料,nginx将關閉連接配接,預設值是60秒
    send_timeout 10;

#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壓縮輸出
    gzip on; 
    #最小壓縮檔案大小
    gzip_min_length 1k; 
    #壓縮緩沖區
    gzip_buffers 4 16k;
    #壓縮版本(預設1.1,前端如果是squid2.5請使用1.0)
    gzip_http_version 1.0;
    #壓縮等級 1-9 等級越高,壓縮效果越好,節約寬帶,但CPU消耗大
    gzip_comp_level 2;
    #壓縮類型,預設就已經包含text/html,是以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
    gzip_types text/plain application/x-javascript text/css application/xml;
    #前端緩存伺服器緩存經過壓縮的頁面
    gzip_vary on;
    
(4)虛拟主機基本設定
#虛拟主機定義
    server {
        #監聽端口
        listen       80;
        #通路域名
        server_name  localhost;
        #編碼格式,若網頁格式與此不同,将被自動轉碼
        #charset koi8-r;
        #虛拟主機通路日志定義
        access_log  logs/host.access.log  main;
        #對URL進行比對
        location / {
            # 使用者浏覽器緩存時間設定,緩存時間為1天
            # expires 1d;
            #通路路徑,可相對也可絕對路徑
            root   html;
            #首頁檔案。以下按順序比對
            index  index.html index.htm;
        }

#錯誤資訊傳回頁面
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

#通路URL以.php結尾則自動轉交給127.0.0.1
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
#php腳本請求全部轉發給FastCGI處理
        # 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_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

#禁止通路.ht頁面 (需ngx_http_access_module子產品)
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
#HTTPS虛拟主機定義
    # 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;
    #    }
    #}
    
(5)nginx狀态監控
#Nginx運作狀态,StubStatus子產品擷取Nginx自啟動的工作狀态(編譯時要開啟對應功能)
        #location /NginxStatus {
        #    #啟用StubStatus的工作通路狀态    
        #    stub_status    on;
        #    #指定StubStaus子產品的通路日志檔案
        #    access_log    logs/Nginxstatus.log;
        #    #Nginx認證機制(需Apache的htpasswd指令生成)
        #    #auth_basic    "NginxStatus";
        #    #用來認證的密碼檔案
        #    #auth_basic_user_file    ../htpasswd;    
        #}
通路:http://IP/NginxStatus(測試就不加密碼驗證相關) 

(6)反向代理
#以下配置追加在HTTP的全局變量中

#nginx跟後端伺服器連接配接逾時時間(代理連接配接逾時)
proxy_connect_timeout      5;
#後端伺服器資料回傳時間(代理發送逾時)
proxy_send_timeout         5;
#連接配接成功後,後端伺服器響應時間(代理接收逾時)
proxy_read_timeout         60;
#設定代理伺服器(nginx)儲存使用者頭資訊的緩沖區大小
proxy_buffer_size          16k;
#proxy_buffers緩沖區,網頁平均在32k以下的話,這樣設定
proxy_buffers              4 32k;
#高負荷下緩沖大小(proxy_buffers*2)
proxy_busy_buffers_size    64k;
#設定緩存檔案夾大小,大于這個值,将從upstream伺服器傳
proxy_temp_file_write_size 64k;
#反向代理緩存目錄
proxy_cache_path /data/proxy/cache levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=1g;
#levels=1:2 設定目錄深度,第一層目錄是1個字元,第2層是2個字元
#keys_zone:設定web緩存名稱和記憶體緩存空間大小
#inactive:自動清除緩存檔案時間。
#max_size:硬碟空間最大可使用值。
#指定臨時緩存檔案的存儲路徑(路徑需和上面路徑在同一分區)
proxy_temp_path /data/proxy/temp

#反向代理服務配置
server {
    #偵聽的80端口
    listen       80;
    server_name  localhost;
    location / {
        #反向代理緩存設定指令(proxy_cache zone|off,預設關閉是以要設定)
        proxy_cache cache_one;
        #對不同的狀态碼緩存不同時間
        proxy_cache_valid 200 304 12h;
        #設定以什麼樣參數擷取緩存檔案名
        proxy_cache_key $host$uri$is_args$args;
        #後7端的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;   
        #代理設定
        proxy_pass   http://IP; 
        #檔案過期時間控制
        expires    1d;
    }
    #配置手動清除緩存(實作此功能需第三方子產品 ngx_cache_purge)
    #http://www.123.com/2017/0316/17.html通路
    #http://www.123.com/purge/2017/0316/17.html清楚URL緩存
    location ~ /purge(/.*) {
        allow    127.0.0.1;
        deny    all;
        proxy_cache_purge    cache_one    $host$1$is_args$args;
    }
    #設定擴充名以.jsp、.php、.jspx結尾的動态應用程式不做緩存
    location ~.*\.(jsp|php|jspx)?$ { 
        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://http://IP;
    }

(7)負載均衡
#負載均衡伺服器池
upstream my_server_pool {
    #排程算法
    #1.輪循(預設)(weight輪循權值)
    #2.ip_hash:根據每個請求通路IP的hash結果配置設定。(會話保持)
    #3.fair:根據後端伺服器響應時間最短請求。(upstream_fair子產品)
    #4.url_hash:根據通路的url的hash結果配置設定。(需hash軟體包)
    #參數:
    #down:表示不參與負載均衡
    #backup:備份伺服器
    #max_fails:允許最大請求錯誤次數
    #fail_timeout:請求失敗後暫停服務時間。
    server 192.168.1.109:80 weight=1 max_fails=2 fail_timeout=30;
    server 192.168.1.108:80 weight=2 max_fails=2 fail_timeout=30;
}
#負載均衡調用
server {
    ...
    location / {
    proxy_pass http://my_server_pool;
    }
}

(8)URL重寫
#根據不同的浏覽器URL重寫
if($http_user_agent ~ Firefox){
rewrite ^(.*)$  /firefox/$1 break; 
}
if($http_user_agent ~ MSIE){
rewrite ^(.*)$  /msie/$1 break; 
}

#實作域名跳轉
location / {
    rewrite ^/(.*)$ https://web8.example.com$1 permanent;
}

(9)IP限制
#限制IP通路
location / {
    deny 192.168.0.2;
    allow 192.168.0.0/24;
    allow 192.168.1.1;
    deny all;
}

      
Nginx 配置檔案解析
Nginx 配置檔案解析
#!/bin/bash
#chkconfig: 2345 80 90
#description:auto_run
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
# Check if user is root
if [ $(id -u) != "0" ]; then
   echo "Error: You must be root to run this script!\n"
   exit 1
fi
NGINXDAEMON=/usr/local/nginx/sbin/nginx
PIDFILE=/usr/local/nginx/logs/nginx.pid
function_start()
{
   echo -en "\033[32;49;1mStarting nginx......\n"
   echo -en "\033[39;49;0m"  
   if [ -f $PIDFILE ]; then
     printf "Nginx is runing!\n"
     exit 1
   else  
       $NGINXDAEMON
       printf "Nginx is the successful start!\n"
   fi
}
function_stop()
{
   echo -en "\033[32;49;1mStoping nginx......\n"
   echo -en "\033[39;49;0m"
   if  [ -f $PIDFILE ]; then
       kill `cat $PIDFILE`
       printf "Nginx program is stoped\n"
   else  
       printf  "Nginx program is not runing!\n"
   fi
}
function_reload()
{
   echo -en "\033[32;49;1mReload nginx......\n"
   echo -en "\033[39;49;0m"
   function_stop
   function_start
}
function_restart()
{
   echo -en "\033[32;49;1mRestart nginx......\n"
   echo -en "\033[39;49;0m"
   printf "Reload Nginx configure...\n"
   $NGINXDAEMON -t
   kill -HUP `cat $PIDFILE`
   printf "Nginx program is reloding!\n"
}
function_kill()
{
   killall nginx
}
function_status()
{
   if ! ps -ef|grep -v grep|grep 'nginx:' > /dev/null 2>&1
   then
       printf "Nginx is down!!!\n"
   else
       printf "Nginx is running now!\n"
   fi
}
if [ "$1" = "start" ]; then
   function_start
elif [ "$1" = "stop" ]; then
   function_stop
elif [ "$1" = "reload" ]; then
   function_reload
elif [ "$1" = "restart" ]; then
   function_restart
elif [ "$1" = "kill" ]; then
   function_kill
elif [ "$1" = "status" ]; then
   function_status
else
   echo -en "\033[32;49;1m Usage: nginx {start|stop|reload|restart|kill|status}\n"
   echo -en "\033[39;49;0m"
fi      

nginx 運作腳本

參考連結:https://www.cnblogs.com/hunttown/p/5759959.html

繼續閱讀