nginx配置

由 livisky 创建, 最后一次修改 2017-01-19

网站上线了,发现慢点够可以,特别是图片及静态资源加载,是什么原因?

nodejs的弊端,不太适合处理静态资源,配合nginx的反向代理,速度能提升不少。
1、gzip默认没有开启
2、node应用的静态资源,交给nginx处理,用nginx转发,实现动静态分离
3、开启静态资源缓存

一、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应用动静态资源分离

1、可以考虑用个二级域名,如http://static.jsout.com
2、如果不用二级域名,也可以通过nginx配置目录达到目的

server {
    ...
    listen 80;
    server_name www.jsout.com jsout.com;
    root /var/www/jsout/liblog/www;  //指定静态资源根目录
    set $node_port 8361;
    ...

三、开启缓存

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

四、附完整的基于thinkjs的nodejs应用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;
    }
}   
}
以上内容是否对您有帮助:
python零基础入门到爬虫实战
二维码
建议反馈
二维码