以下就是我們整理的nginx常見的問題,解決辦法我們例舉了1-2種,大家可以都測試下。
常見問題
問題一:相同server_name多個虛擬主機優先級訪問
server{ listen 80; server_name server1; location{...}}server{ listen 80; server_name server2; location{...}}
解決方法:
配置兩個conf文件:server1.conf 和 server2.conf
根據Linux系統中文件順序讀取
問題二:location匹配優先級
location = /code1/ { rewrite ^(.*)$ /code1/index.html break;}location ~ /code.* { rewrite ^(.*)$ /code3/index.html break;}location ^~ /code { rewrite ^(.*)$ /code2/index.html break;}
知識填坑:
=:進行普通字符精確匹配,完全匹配
^~:普通字符匹配,使用前綴匹配
~ /~*:表示執行一個正則匹配()
解決方法:
根據匹配找到最優匹配
優先級:完全匹配>正則匹配>前綴匹配
問題三:try_files使用
location / { try_files $uri $uri/ /index.html;}
解決方法:
按順序檢查文件是否存在
問題四:Nginx的alias和root區別
location /request_path/img/ { root /local_path/img/;}location /request_path/img/ { alias /local_path/img/;}
解決方法:
root設置,最終請求的路徑為/local_path/img/request_path/img/
alias設置,最終請求為/local_path/img/
問題五:通過多層代理,傳遞用戶真實IP
解決方法:
set x_real_ip=$remote_addr$x_real_ip=真實IP
性能優化問題
優化考慮點:
當前系統結構瓶頸,如觀察指標、壓力測試
了解業務模式,如接口業務類型、系統層次化結構
性能與安全
接口壓力測試工具:ab
安裝:yum install httpd-tools
使用:ab -n 2000 -c 20 http://127.0.0.1/
nginx關于系統的優化點:
網絡、系統、服務、程序、數據庫
控制文件句柄數量,文件句柄就是一個索引
CPU親和,使進程不會在處理器間頻繁遷移,減少性能損耗
vim /etc/nginx/nginx.confuser 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參數
新聞熱點
疑難解答