Nginx 經常使用配置彙總!從入門到幹活足矣

衆所周知,Nginx 是 Apache服務不錯的替代品。其特色是佔有內存少,併發能力強,事實上 Nginx 的併發能力在同類型的網頁服務器中表現較好,所以國內知名大廠例如:淘寶,京東,百度,新浪,網易,騰訊等等都在使用Nginx網站。javascript

圖片

Nginx簡介

Nginx 是開源、高性能、高可靠的 Web 和反向代理服務器,並且支持熱部署,同時也提供了 IMAP/POP3/SMTP 服務,能夠不間斷運行,提供熱更新功能。佔用內存少、併發能力強,最重要的是,Nginx 是免費的並能夠商業化,配置使用都比較簡單。css

圖片

Nginx 特色
  • 高併發、高性能html

  • 模塊化架構使得它的擴展性很是好java

  • 異步非阻塞的事件驅動模型這點和 Node.js 類似nginx

  • 無需重啓可不間斷運行web

  • 熱部署、平滑升級正則表達式

  • 徹底開源,生態好json

Nginx 最重要的幾個使用場景:
  • 靜態資源服務後端

  • 反向代理服務,包括緩存、負載均衡等瀏覽器

  • API 服務,OpenResty

因此,今天民工哥就給你們整理一份 Nginx的經常使用配置清單,供你們學習與生產配置參考使用。主要包括如下三個方面:

  • 基礎配置

  • 高級配置

  • 安全配置

基礎配置

去掉不用的 Nginx 模塊

./configure --without-module1 --without-module2 --without-module3例如:./configure --without-http_dav_module --withouthttp_spdy_module#注意事項:配置指令是由模塊提供的。確保你禁用的模塊不包含你須要使用的指令!在決定禁用模塊以前,應該檢查Nginx文檔中每一個模塊可用的指令列表。
複製代碼

Nginx 版本的平滑升級與回滾

1分鐘搞定 Nginx 版本的平滑升級與回滾

進程相關的配置

worker_processes 8;#Nginx 進程數,建議按照CPU數目來指定,通常爲它的倍數 (如,2個四核的CPU計爲8)。worker_rlimit_nofile 65535;  #一個Nginx 進程打開的最多文件描述符數目worker_connections 65535;#每一個進程容許的最多鏈接數
複製代碼

監聽端口

server {        listen       80;   #監聽端口        server_name  www.mingongge.com;  #域名信息        location / {            root   /www/www;   #網站根目錄            index  index.html index.htm;  #默認首頁類型            deny 192.168.2.11;   #禁止訪問的ip地址,能夠爲all            allow 192.168.3.44; #容許訪問的ip地址,能夠爲all        }        }           
複製代碼

小技巧補充:域名匹配的四種寫法

精確匹配:server_name www.mingongge.com ;左側通配:server_name *.mingongge.com ;右側統配:server_name www.mingongge.* ;正則匹配:server_name ~^www\.mingongge\.*$ ;匹配優先級:精確匹配 > 左側通配符匹配 > 右側通配符匹配 > 正則表達式匹配
複製代碼

配置 Nginx 狀態頁面

[root@proxy ~]# cat /usr/local/nginx/conf/nginx.conf… …location /NginxStatus {      stub_status           on;      access_log            on;      auth_basic            "NginxStatus";      auth_basic_user_file  conf/htpasswd;        }… …[root@proxy ~]# /usr/local/nginx/sbin/nginx -s reload
複製代碼

Nginx 日誌(訪問與錯誤日誌管理)

error_log  /var/log/nginx/error.log warn;#配置錯誤日誌的級別及存儲目錄events {    worker_connections  1024;}http {..................    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  /var/log/nginx/access.log main;    #配置訪問日誌存儲目錄}
複製代碼

以上配置只是Nginx自身關於日誌的基本配置,在實際生產環境中,咱們須要收集日誌、分析日誌,才定更好的去定位問題,推薦給你們:超強幹貨!經過filebeat、logstash、rsyslog 幾種方式採集 nginx 日誌

http 相關的配置

http {    sendfile  on                  #高效傳輸文件的模式 必定要開啓    keepalive_timeout   65        #客戶端服務端請求超時時間 }
複製代碼

靜態資源配置

server {  listen 80;  server_name mingongge.com;  location /static {        root /wwww/web/web_static_site;   }}
複製代碼

也可使用下面的方法

location /image { alias /web/nginx/static/image/;}注意:使用alias末尾必定要添加/,而且它只能位於location中
複製代碼

反向代理

好比生產環境(同一臺服務中)有不一樣的項目,這個就比較實用了,用反向代理去作請示轉發。

http {.............    upstream product_server{        127.0.0.1:8081;    }    upstream admin_server{        127.0.0.1:8082;    }    upstream test_server{        127.0.0.1:8083;    }server {        #默認指向product的server  location / {      proxy_pass http://product_server;      }  location /product/{      proxy_pass http://product_server;     }  location /admin/ {      proxy_pass http://admin_server;     }  location /test/ {      proxy_pass http://test_server;      }    }}
複製代碼

更多關於 Nginx 實踐:location 路徑匹配

負載均衡

upstream server_pools {   server 192.168.1.11:8880   weight=5;  server 192.168.1.12:9990   weight=1;  server 192.168.1.13:8989   weight=6;  #weigth參數表示權值,權值越高被分配到的概率越大}server {    listen 80;   server_name mingongge.com;  location / {      proxy_pass http://server_pools;    }}
複製代碼

代理相關的其它配置

proxy_connect_timeout 90;  #nginx跟後端服務器鏈接超時時間(代理鏈接超時)proxy_send_timeout 90;     #後端服務器數據回傳時間(代理髮送超時)proxy_read_timeout 90;     #鏈接成功後,後端服務器響應時間(代理接收超時)proxy_buffer_size 4k;      #代理服務器(nginx)保存用戶頭信息的緩衝區大小proxy_buffers 4 32k;      #proxy_buffers緩衝區proxy_busy_buffers_size 64k;     #高負荷下緩衝大小(proxy_buffers*2)proxy_temp_file_write_size 64k;  #設定緩存文件夾大小proxy_set_header Host $host; proxy_set_header X-Forwarder-For $remote_addr;  #獲取客戶端真實IP
複製代碼

高級配置

重定向配置

location / { return 404; #直接返回狀態碼}location / { return 404 "pages not found"; #返回狀態碼 + 一段文本}location / { return 302 /blog ; #返回狀態碼 + 重定向地址}location / { return https://www.mingongge.com ; #返回重定向地址}
複製代碼

示例以下

server { listen 80;server_name www.mingongge.com;return 301 http://mingongge.com$request_uri;}server {listen 80; server_name www.mingongge.com; location /cn-url {    return 301 http://mingongge.com.cn;    }}

server{  listen 80;  server_name mingongge.com; # 要在本地hosts文件進行配置  root html;  location /search {   rewrite ^/(.*) https://www.mingongge.com redirect;  }    location /images {   rewrite /images/(.*) /pics/$1;  }    location /pics {   rewrite /pics/(.*) /photos/$1;  }    location /photos {    }}
複製代碼

設置緩衝區容量上限

這樣的設置能夠阻止緩衝區溢出攻擊(一樣是Server模塊)

client_body_buffer_size 1k;client_header_buffer_size 1k;client_max_body_size 1k;large_client_header_buffers 2 1k;#設置後,無論多少HTTP請求都不會使服務器系統的緩衝區溢出了
複製代碼

限制最大鏈接數

在http模塊內server模塊外配置limit_conn_zone,配置鏈接的IP,在http,server或location模塊配置limit_conn,能配置IP的最大鏈接數。

limit_conn_zone $binary_remote_addr zone=addr:5m;limit_conn addr 1;
複製代碼

Gzip壓縮

gzip_types  #壓縮的文件類型 text/plain text/css  application/json  application/x-javascript  text/xml application/xml  application/xml+rss  text/javascriptgzip on;#採用gzip壓縮的形式發送數據gzip_disable "msie6"#爲指定的客戶端禁用gzip功能gzip_static;#壓縮前查找是否有預先gzip處理過的資源gzip_proxied any;#容許或者禁止壓縮基於請求和響應的響應流gzip_min_length  1000;#設置對數據啓用壓縮的最少字節數gzip_comp_level 6;#設置數據的壓縮等級
複製代碼

緩存配置

open_file_cache#指定緩存最大數目以及緩存的時間open_file_cache_valid#在open_file_cache中指定檢測正確信息的間隔時間open_file_cache_min_uses   #定義了open_file_cache中指令參數不活動時間期間裏最小的文件數open_file_cache_errors     #指定了當搜索一個文件時是否緩存錯誤信息location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$#指定緩存文件的類型        {        expires 3650d;               #指定緩存時間        }        location ~ .*\.(js|css)?$        {        expires 3d;                             }
複製代碼

SSL 證書配及跳轉HTTPS配置

server {      listen 192.168.1.250:443 ssl;      server_tokens off;      server_name mingonggex.com www.mingonggex.com;      root /var/www/mingonggex.com/public_html;      ssl_certificate /etc/nginx/sites-enabled/certs/mingongge.crt;      ssl_certificate_key /etc/nginx/sites-enabled/certs/mingongge.key;      ssl_protocols TLSv1 TLSv1.1 TLSv1.2;}# Permanent Redirect for HTTP to HTTPSserver {  listen 80;  server_name mingongge.com; https://$server_name$request_uri;}
複製代碼

流量鏡像功能

location / {    mirror /mirror;    proxy_pass http://backend;}location = /mirror {    internal;    proxy_pass http://test_backend$request_uri;}
複製代碼

限流功能

流量限制配置兩個主要的指令,limit_req_zonelimit_req

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;server {    location /login/ {        limit_req zone=mylimit;        proxy_pass http://my_upstream;    }}
複製代碼

更多、更詳細的限流配置請參考:葵花寶典!一文搞定 Nginx 限流配置

Nginx經常使用的內置變量

圖片

安全配置

禁用server_tokens項

server_tokens在打開的狀況下會使404頁面顯示Nginx的當前版本號。這樣作顯然不安全,由於黑客會利用此信息嘗試相應Nginx版本的漏洞。只須要在nginx.conf中http模塊設置server_tokens off便可,例如:

server {    listen 192.168.1.250:80;    Server_tokens off;    server_name mingongge.com www.mingongge.com;    access_log /var/www/logs/mingongge.access.log;    error_log /var/www/logs/mingonggex.error.log error;    root /var/www/mingongge.com/public_html;    index index.html index.htm;}#重啓Nginx後生效:
複製代碼

禁止非法的HTTP User Agents

User Agent是HTTP協議中對瀏覽器的一種標識,禁止非法的User Agent能夠阻止爬蟲和掃描器的一些請求,防止這些請求大量消耗Nginx服務器資源。

爲了更好的維護,最好建立一個文件,包含不指望的user agent列表例如/etc/nginx/blockuseragents.rules包含以下內容:

map $http_user_agent $blockedagent {    default 0;    ~*malicious 1;    ~*bot 1;    ~*backdoor 1;    ~*crawler 1;    ~*bandit 1;}
複製代碼

而後將以下語句放入配置文件的server模塊內

include /etc/nginx/blockuseragents.rules;並加入if語句設置阻止後進入的頁面:
複製代碼

阻止圖片外鏈

location /img/ {      valid_referers none blocked 192.168.1.250;        if ($invalid_referer) {          return 403;      }}
複製代碼

封殺惡意訪問

挺帶勁!經過 Nginx 來實現封殺惡意訪問

禁掉不須要的 HTTP 方法

一些web站點和應用,能夠只支持GET、POST和HEAD方法。在配置文件中的 serve r模塊加入以下方法能夠阻止一些欺騙攻擊

if ($request_method !~ ^(GET|HEAD|POST)$) {    return 444;}
複製代碼

禁止 SSL 而且只打開 TLS

儘可能避免使用SSL,要用TLS替代,如下配置能夠放在Server模塊內

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
複製代碼

經過這一系列的配置以後,相信你的Nginx服務器足夠應付實際生產需求了。

也歡迎你們積極留言補充這份經常使用配置清單,以便它更完整、更完善。

相關文章
相關標籤/搜索