不知道可是很常見的nginx問題

nginx使用問題及解決方法

常見問題

問題一:相同server_name多個虛擬主機優先級訪問php

server{
  listen 80;
  server_name server1;
  location{...}
}

server{
  listen 80;
  server_name server2;
  location{...}
}

解決方法:html

  • 配置兩個conf文件:server1.conf 和 server2.conf
  • 根據Linux系統中文件順序讀取

問題二:location匹配優先級nginx

location = /code1/ {
  rewrite ^(.*)$ /code1/index.html break;
}

location ~ /code.* {
  rewrite ^(.*)$ /code3/index.html break;
}

location ^~ /code {
  rewrite ^(.*)$ /code2/index.html break;
}

知識填坑:git

  • =:進行普通字符精確匹配,徹底匹配
  • ^~:普通字符匹配,使用前綴匹配
  • ~ \~*:表示執行一個正則匹配()

解決方法:github

  • 根據匹配找到最優匹配
  • 優先級:徹底匹配>正則匹配>前綴匹配

問題三:try_files使用正則表達式

location / {
  try_files $uri $uri/ /index.html;
}

解決方法:shell

  • 按順序檢查文件是否存在

問題四:Nginx的alias和root區別數據庫

location /request_path/img/ {
  root /local_path/img/;
}

location /request_path/img/ {
  alias /local_path/img/;
}

解決方法:vim

  • root設置,最終請求的路徑爲/local_path/img/request_path/img/
  • alias設置,最終請求爲/local_path/img/

問題五:經過多層代理,傳遞用戶真實IP安全

解決方法:

set x_real_ip=$remote_addr
$x_real_ip=真實IP

性能優化問題

優化考慮點:

  • 當前系統結構瓶頸,如觀察指標、壓力測試
  • 瞭解業務模式,如接口業務類型、系統層次化結構
  • 性能與安全

接口壓力測試工具:ab

nginx關於系統的優化點:

  • 網絡、系統、服務、程序、數據庫
  • 控制文件句柄數量,文件句柄就是一個索引
  • CPU親和,使進程不會在處理器間頻繁遷移,減小性能損耗
vim /etc/nginx/nginx.conf

user nginx;
worker_processes 16;
worker_cpu_affinity auto;
worker_rlimit_nofile 15535;
events{
  use epoll;
  worker_connections 10240;
}
http{
  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  #Charset
  charset utf-8;

  log_format main '';
  access_log /var/log/nginx/access.log main;

  #Core module
  sendfile on;
  keepalive_timeout 65;

  #Gzip module
  gzip on;
  gzip_disable "MSIE [1-6]\.";
  gzip_http_version 1.1;

  #Virtal server
  include /etc/nginx/conf.d/*.conf;
}

nginx安全問題及防範策略

惡意行爲

問題:爬蟲行爲和惡意抓取、資源盜用

解決方法:

  • 基礎防盜鏈功能:不讓惡意用戶輕易的爬取網站對外數據
  • secure_link_module模塊:對數據安全性提升加密驗證和失效性,對一些重要數據使用
  • access_module模塊:對後臺、部分用戶服務的數據提供IP監控,如規定IP等

應用層攻擊

問題一:後臺密碼撞庫,經過密碼字典不斷對後臺系統登陸性嘗試,獲取後臺密碼

解決方法:

  • 後臺密碼複雜的,大小寫數字字符等
  • 預警機制,同一IP的頻繁訪問
  • access_module模塊:對後臺、部分用戶服務的數據提供IP監控

問題二:文件上傳漏洞,利用能夠上傳的接口將惡意代碼植入服務器中,再經過url訪問以執行

解決方法:
針對一些木馬和後綴等作必定的處理

location ^~ /upload{
  root /usr/share/html;
  if($request_filename ~*(.*)\.php){
    return 403;  #拒絕訪問
  }
}

問題三:SQL注入,利用未過濾或未審覈的用戶輸入的攻擊手段,讓應用運行本不該該運行的SQL代碼

解決方法:

  • 針對' or 1=1 #等常見注入代碼進行檢測
  • 搭建安全waf,針對滲透規則寫正則表達式

nginx防攻擊策略

使用nginx+Lua搭建安全waf防火牆

防火牆功能:

  • 攔截Cookie類型攻擊
  • 攔截異常post請求
  • 攔截cc攻擊,頻繁訪問
  • 攔截URL,不想暴露的接口
  • 攔截arg參數

推薦已寫好waf:https://github.com/loveshell/...

相關文章
相關標籤/搜索