Nginx 常用配置匯總!從入門到干活足矣


轉載自公眾號:民工哥

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

 

 

Nginx簡介

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

 

Nginx 特點

  • 高並發、高性能
  • 模塊化架構使得它的擴展性非常好
  • 異步非阻塞的事件驅動模型這點和 Node.js 相似
  • 無需重啟可不間斷運行
  • 熱部署、平滑升級
  • 完全開源,生態好
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/javascript

gzip 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 HTTPS
server 
{  
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服務器足夠應付實際生產需求了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM