nginx配置

2018-01-23 10:01 更新

網(wǎng)站上線了,發(fā)現(xiàn)慢點(diǎn)夠可以,特別是圖片及靜態(tài)資源加載,是什么原因?

nodejs的弊端,不太適合處理靜態(tài)資源,配合nginx的反向代理,速度能提升不少。

1、gzip默認(rèn)沒有開啟

2、node應(yīng)用的靜態(tài)資源,交給nginx處理,用nginx轉(zhuǎn)發(fā),實(shí)現(xiàn)動(dòng)靜態(tài)分離

3、開啟靜態(tài)資源緩存

一、nginx配置開啟gzip

     gzip_vary on;
     gzip_proxied any;
     gzip_comp_level 6;
     gzip_buffers 16 8k;
     gzip_http_version 1.1;
     gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
     gzip on;
     gzip_disable "msie6";

二、node應(yīng)用動(dòng)靜態(tài)資源分離

1、可以考慮用個(gè)二級(jí)域名,如http://static.jsout.com
2、如果不用二級(jí)域名,也可以通過nginx配置目錄達(dá)到目的

server {
    ...
    listen 80;
    server_name www.jsout.com jsout.com;
    root /var/www/jsout/liblog/www;  //指定靜態(tài)資源根目錄
    set $node_port 8361;
    ...

三、開啟緩存

server {
    ...
    location ~ /static/ {
        etag         on;
        expires      max;
    }
    ...
    }

四、附完整的基于thinkjs的nodejs應(yīng)用nginx配置(以前端匯http://www.jsout.com為例)

worker_processes  1;
events {
    worker_connections  1024;
}
http{
   include       mime.types;


     default_type  application/octet-stream;


     sendfile on;
     tcp_nopush on;
     tcp_nodelay on;


     keepalive_timeout 60;


     client_header_buffer_size 4k;


     open_file_cache max=51200 inactive=20s;
     open_file_cache_valid 30s;
     open_file_cache_min_uses 1;


     types_hash_max_size 2048;
     client_max_body_size 10m;


     gzip_vary on;
     gzip_proxied any;
     gzip_comp_level 6;
     gzip_buffers 16 8k;
     gzip_http_version 1.1;
     gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
     gzip on;
     gzip_disable "msie6";

     
server {
    listen 80;
    server_name www.jsout.com jsout.com;
    root /var/www/jsout/liblog/www;
    set $node_port 8361;


    index index.js index.html index.htm;
    if ( -f $request_filename/index.html ){
        rewrite (.*) $1/index.html break;
    }
    if ( !-f $request_filename ){
        rewrite (.*) /index.js;
    }
    location = /index.js {
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_pass http://127.0.0.1:$node_port$request_uri;
        proxy_redirect off;
    }

    
    location = /production.js {
        deny all;
    }


    location = /testing.js {
        deny all;
    }


    location ~ /static/ {
        etag         on;
        expires      max;
    }
}   
}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)