1. 程式人生 > >nginx優化及配置

nginx優化及配置

協議 expr x-real-ip java app load all prot deny

vi /usr/local/nginx/conf/nginx.conf
user www www;
worker_processes 4;

#錯誤日誌存放目錄
error_log /usr/local/nginx/logs/error.log;
error_log /usr/local/nginx/logs/error.log notice;
error_log /usr/local/nginx/logs/error.log info;

#進程pid存放位置
pid /usr/local/nginx/logs/nginx.pid;

#最大文件打開數(連接),可設置為系統優化後的ulimit -HSn的結果
worker_rlimit_nofile 51200;

#cpu親和力配置,讓不同的進程使用不同的cpu
worker_cpu_affinity 0001 0010 0100 1000 0001 00100100 1000;

#工作模式及連接數上限
events {
use epoll; #epoll是多路復用IO(I/O Multiplexing)中的一種方式,但是僅用於linux2.6以上內核,可以大大提高nginx的性能
worker_connections 1024; #單個後臺worker process進程的最大並發鏈接數
}

#設定http服務器,利用它的反向代理功能提供負載均衡支持
http {
#設定mime類型
include mime.types; #文件擴展名與類型映射表

default_type application/octet-stream; #默認文件類型

include /usr/local/nginx/conf/proxy.conf;

#設置日誌模式
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 logs/access.log main;

#設定請求緩存
server_names_hash_bucket_size 128;
client_header_buffer_size 512K;
large_client_header_buffers 4 512k;
#client_max_body_size 100m;

#隱藏響應header和錯誤通知中的版本號
server_tokens off;

#開啟高效傳輸模式
sendfile on;

#激活tcp_nopush參數可以允許把httpresponse header和文件的開始放在一個文件裏發布,積極的作用是減少網絡報文段的數量。
tcp_nopush on;

#激活tcp_nodelay,內核會等待將更多的字節組成一個數據包,從而提高I/O性能
tcp_nodelay on;

#連接超時時間,單位是秒
keepalive_timeout 60;

#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 on;

#設置允許壓縮的頁面最小字節數,頁面字節數從header頭的Content-Length中獲取。默認值是0,表示不管頁面多大都進行壓縮。建議設置成大於1K。如果小於1K可能會越壓越大。
gzip_min_length 1k;

#壓縮緩沖區大小。表示申請4個單位為16K的內存作為壓縮結果流緩存,默認值是申請與原始數據大小相同的內存空間來存儲gzip壓縮結果。
gzip_buffers 4 16k;

#壓縮版本(默認1.1,前端為squid2.5時使用1.0)用於設置識別HTTP協議版本,默認是1.1,目前大部分瀏覽器已經支持GZIP解壓,使用默認即可。
gzip_http_version 1.1;

#壓縮比率。用來指定GZIP壓縮比,1壓縮比最小,處理速度最快;9壓縮比最大,傳輸速度快,但處理最慢,也比較消耗cpu資源。
gzip_comp_level 2;

#用來指定壓縮的類型,“text/html”類型總是會被壓縮
gzip_types text/plain application/x-javascript text/css application/xml;

#vary header支持。該選項可以讓前端的緩存服務器緩存經過GZIP壓縮的頁面,例如用Squid緩存經過Nginx壓縮的數據。
gzip_vary on;

#開啟ssi支持,默認是off
ssi on;
ssi_silent_errors on;

#反向代理負載均衡設定部分
#upstream表示負載服務器池,定義名字為tomcat_pool的服務器池
#此處為你tomcat的地址,可以寫多個tomcat地址
upstream tomcat_pool {
server 192.168.254.133:8080 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.254.132:8080 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.254.131:8080 weight=1 max_fails=2 fail_timeout=30s;
#設置由 fail_timeout 定義的時間段內連接該主機的失敗次數,以此來斷定 fail_timeout 定義的時間段內該主機是否可用。默認情況下這個數值設置為 1。零值的話禁用這個數量的嘗試。
#設置在指定時間內連接到主機的失敗次數,超過該次數該主機被認為不可用。
#這裏是在30s內嘗試2次失敗即認為主機不可用!
}

#基於域名的虛擬主機
server {

listen       80;   #監聽端口
server_name  www.web2.com;#此處替換為你自己的網址,如有多個中間用空格
index index.html index.htm index.php  index.html;#設定訪問的默認首頁地址     
root /home/www/web; #設定網站的資源存放路徑 

#charset koi8-r;

#access_log  logs/host.access.log  main;

location / {

root html;

    index index.jsp index.html index.htm;
}

location ~ \.(jsp|jspx|dp)?$ #所有JSP的頁面均交由tomcat處理
{
    proxy_set_header  Host $host;
    proxy_set_header  X-Real-IP $remote_addr; 
    proxy_pass http://tomcat_pool;#轉向tomcat處理
}

#設定訪問靜態文件直接讀取不經過tomcat
location ~ .*\.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$ 
 {
     expires  30d;
 }

 #將符合js,css文件的等設定expries緩存參數,要求瀏覽器緩存。
 location ~ .*\.(js|css)?$
 {
      expires  30d;  #客戶端緩存上述js,css數據30天
 }

access_log  /usr/local/nginx/logs/ubitechtest.log main;#設定訪問日誌的存放路徑  

error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   html;
}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#

#符合php擴展名的請求調度到fcgi server
location ~ \.php$ {
    fastcgi_pass   127.0.0.1:9000;  #拋給本機的9000端口
    fastcgi_index  index.php;   #設定動態首頁
    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    include        fastcgi_params;
    #include        fcgi.conf;
}

##add by 20140321#######nginx防sql註入##########
###start####
if ( $query_string ~ ".[\;‘\<\>]." ){
return 444;
}
if ($query_string ~
".(insert|select|delete|update|count|*|%|master|truncate|declare|\‘|\;|and|or|(|)|exec). ")
{
return 444;
}
if ($request_uri ~ "(cost()|(concat()") {
return 444;
}
if ($request_uri ~
"[+|(%20)]union[+|(%20)]") {
return 444;
}
if ($request_uri ~ "[+|(%20)]and[+|(%20)]") {
return 444;
}
if ($request_uri ~
"[+|(%20)]select[+|(%20)]") {
return 444;
}
set $block_file_injections 0;
if ($querystring ~ "[a-zA-Z0-9]=(..//?)+") {
set $block_file_injections 1;
}
if ($querystring ~ "[a-zA-Z0-9]=/([a-z0-9_.]//?)+") {
set $block_file_injections 1;
}
if ($block_file_injections = 1) {
return 448;
}
set $block_common_exploits 0;
if ($query_string ~ "(<|%3C).script.(>|%3E)") {
set $block_common_exploits 1;
}
if ($query_string ~ "GLOBALS(=|[|\%[0-9A-Z]{0,2})") {
set $block_common_exploits 1;
}
if ($query_string ~ "_REQUEST(=|[|\%[0-9A-Z]{0,2})") {
set $block_common_exploits 1;
}
if ($query_string ~ "proc/self/environ") {
set $block_common_exploits 1;
}
if ($querystring ~ "mosConfig[a-zA-Z_]{1,21}(=|\%3D)") {
set $block_common_exploits 1;
}
if ($querystring ~ "base64(en|de)code(.*)") {
set $block_common_exploits 1;
}
if ($block_common_exploits = 1) {
return 444;
}
set $block_spam 0;
if ($query_string ~ "\b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)\b") {
set $block_spam 1;
}
if ($query_string ~ "\b(erections|hoodia|huronriveracres|impotence|levitra|libido)\b") {
set $block_spam 1;
}
if ($query_string ~ "\b(ambien|blue\spill|cialis|cocaine|ejaculation|erectile)\b") {
set $block_spam 1;
}
if ($query_string ~ "\b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)\b") {
set $block_spam 1;
}
if ($block_spam = 1) {
return 444;
}
set $block_user_agents 0;
if ($http_user_agent ~ "Wget") {
set $block_user_agents 1;
}

Disable Akeeba Remote Control 2.5 and earlier

if ($http_user_agent ~ "Indy Library") {
set $block_user_agents 1;
}

Common bandwidth hoggers and hacking tools.

if ($http_user_agent ~ "libwww-perl") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "GetRight") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "GetWeb!") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "Go!Zilla") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "Download Demon") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "Go-Ahead-Got-It") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "TurnitinBot") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "GrabNet") {
set $block_user_agents 1;
}
if ($block_user_agents = 1) {
return 444;
}

###end####
 location ~ ^/list {
     #如果後端的服務器返回502、504、執行超時等錯誤,自動將請求轉發到upstream負載均衡池中的另一臺服務器,實現故障轉移。
     proxy_next_upstream http_502 http_504 error timeout invalid_header;
    # proxy_cache cache_one;
     #對不同的HTTP狀態碼設置不同的緩存時間
     proxy_cache_valid  200 301 302 304 1d;
     #proxy_cache_valid  any 1d;
     #以域名、URI、參數組合成Web緩存的Key值,Nginx根據Key值哈希,存儲緩存內容到二級緩存目錄內
     proxy_cache_key $host$uri$is_args$args;
     proxy_set_header Host  $host;
     proxy_set_header X-Forwarded-For  $remote_addr;
     proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie";
     #proxy_ignore_headers Set-Cookie;
     #proxy_hide_header Set-Cookie;
     proxy_pass http://tomcat_pool;
     add_header      Nginx-Cache     "$upstream_cache_status  from  km";

      expires      1d;
    }

#ssl(https)相關設置
#server {
#  listen 13820; #監聽端口
#  server_name localhost;
#  charset utf-8; #gbk,utf-8,gb2312,gb18030 可以實現多種編碼識別
#  ssl on; #開啟ssl
#  ssl_certificate /ls/app/nginx/conf/mgmtxiangqiankeys/server.crt; #服務的證書
#  ssl_certificate_key /ls/app/nginx/conf/mgmtxiangqiankeys/server.key; #服務端key
#  ssl_client_certificate /ls/app/nginx/conf/mgmtxiangqiankeys/ca.crt; #客戶端證書
#  ssl_session_timeout 5m; #session超時時間
#  ssl_verify_client on; # 開戶客戶端證書驗證
#  ssl_protocols SSLv2 SSLv3 TLSv1; #允許SSL協議
#  ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; #加密算法
#  ssl_prefer_server_ciphers on; #啟動加密算法
#  access_log /lw/logs/nginx/dataadmin.test.com.ssl.access.log access ; #日誌格式及日誌存放路徑
#  error_log /lw/logs/nginx/dataadmin.test.com.ssl.error.log; #錯誤日誌存放路徑
#}

# deny access to .htaccess files, if Apache‘s document root
# concurs with nginx‘s one
#
#location ~ /\.ht {
#    deny  all;
#}

}

server {
listen 80;
server_name bbs.yourdomain.com;
location / {
root /home/www/web/springmvc; #設定網站的資源存放路徑
index index.jsp index.htm index.html index.do welcome.jsp;#設定訪問的默認首頁地址
}

location ~ \.(jsp|jspx|dp)?$ #所有JSP的頁面均交由tomcat處理
{
    proxy_set_header  Host $host;
    proxy_set_header  X-Real-IP $remote_addr; 
    proxy_pass http://tomcat_pool;#轉向tomcat處理
}
#設定訪問靜態文件直接讀取不經過tomcat
location ~ .*\.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$ 
 {
     expires  30d;
 }

 location ~ .*\.(js|css)?$
 {
      expires  1h;
 }
access_log  /usr/local/nginx/logs/ubitechztt.log main;#設定訪問日誌的存放路徑     

error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   html;
}

}

another virtual host using mix of IP-, name-, and port-based configuration

#
#server {

listen 8000;

listen somename:8080;

server_name somename alias another.alias;

location / {

root html;

index index.html index.htm;

}

#}
}

nginx優化及配置