Nginx静态fileservicetutorial

LearningNginx静态fileconfiguration, cache策略, 压缩 and optimization, improving网站performance and user体验

静态fileserviceoverview

what is 静态file?

静态file is 指不需要server端processing file, such asHTML, CSS, JavaScript, graph片, 视频, 音频etc.. 这些file in 容不会根据request 不同而变化, 每次request都会返回相同 in 容.

静态fileservice important 性

Nginxserving as静态fileserver 优势

basic静态fileconfiguration

1. basicconfigurationexample

server {
    listen 80;
    server_name example.com;
    
    root /var/www/example.com;
    index index.html index.htm;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

2. configuration说明

3. configuration静态fileclass型

server {
    listen 80;
    server_name example.com;
    
    root /var/www/example.com;
    index index.html;
    
    # configurationMIMEclass型
    types {
        text/html html htm;
        text/css css;
        application/javascript js;
        image/jpeg jpg jpeg;
        image/png png;
        image/gif gif;
        image/svg+xml svg;
        application/pdf pdf;
        application/json json;
    }
    
    location / {
        try_files $uri $uri/ =404;
    }
}

4. 限制访问某些file

server {
    listen 80;
    server_name example.com;
    
    root /var/www/example.com;
    index index.html;
    
    # 禁止访问隐藏file
    location ~ /\. {
        deny all;
    }
    
    # 禁止访问specificfileclass型
    location ~ \.(conf|log)$ {
        deny all;
    }
    
    location / {
        try_files $uri $uri/ =404;
    }
}

静态filecacheconfiguration

what is cache?

cache is a将datastore in 临时位置 techniques, 以便 after 续request可以更 fast 地获取data. for 于静态file, cache可以显著reducingserver load and network传输量, improving网站 response速度.

1. 浏览器cacheconfiguration

server {
    listen 80;
    server_name example.com;
    
    root /var/www/example.com;
    index index.html;
    
    #  for 静态file设置cache头
    location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|pdf|json)$ {
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
        add_header Last-Modified $date_gmt;
        add_header ETag "$entity_tag";
        if_modified_since off;
        etag off;
    }
    
    location / {
        try_files $uri $uri/ =404;
    }
}

2. cache头说明

3. Nginxproxycacheconfiguration

# 定义cachepath
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=static_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
    listen 80;
    server_name example.com;
    
    # usingcache
    location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|pdf|json)$ {
        proxy_cache static_cache;
        proxy_cache_valid 200 30d;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        add_header X-Cache-Status $upstream_cache_status;
        
        root /var/www/example.com;
        try_files $uri $uri/ =404;
    }
    
    location / {
        root /var/www/example.com;
        try_files $uri $uri/ =404;
    }
}

4. cache策略建议

long 期cache策略

for 于不经常变化 静态file (such asgraph片, 第三方libraryetc.) , 可以设置较 long cache时间:

  • graph片file: 30天 or 更 long
  • CSS and JavaScriptfile: 7-30天
  • 字体file: 30天 or 更 long

cache失效策略

for 了确保userable to获取 to 最 new 静态file, 可以adopts以 under 策略:

  • fileversion控制: in file名in添加version号 or 哈希值
  • URLpathversion控制: in URLpathin添加version号
  • cacheverification: usingETag or Last-Modifiedforcacheverification

静态file压缩configuration

what is 压缩?

压缩 is areducingfile big small techniques, through压缩静态file, 可以reducingnetwork传输时间, improving网站 加载速度. Nginxsupport many 种压缩algorithms, such asGzip, Brotlietc..

1. Gzip压缩configuration

http {
    # Gzip压缩configuration
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    
    server {
        listen 80;
        server_name example.com;
        
        root /var/www/example.com;
        index index.html;
        
        location / {
            try_files $uri $uri/ =404;
        }
    }
}

2. Gzipconfigurationparameter说明

3. Brotli压缩configuration (需要Nginx 1.11.5+)

http {
    # Brotli压缩configuration
    brotli on;
    brotli_comp_level 6;
    brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
    
    # Gzip压缩configuration (serving as after 备) 
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_comp_level 6;
    
    server {
        listen 80;
        server_name example.com;
        
        root /var/www/example.com;
        index index.html;
        
        location / {
            try_files $uri $uri/ =404;
        }
    }
}

4. 压缩策略建议

静态fileoptimizationtechniques

1. file组织optimization

server {
    listen 80;
    server_name example.com;
    
    root /var/www/example.com;
    index index.html;
    
    # 静态fileTable of Contents别名
    location /static/ {
        alias /var/www/example.com/static/;
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    }
    
    # graph片Table of Contents
    location /images/ {
        alias /var/www/example.com/images/;
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
    }
    
    # CSS and JavaScriptTable of Contents
    location /assets/ {
        alias /var/www/example.com/assets/;
        expires 7d;
        add_header Cache-Control "public, max-age=604800";
    }
    
    location / {
        try_files $uri $uri/ =404;
    }
}

2. 浏览器cacheoptimization

server {
    listen 80;
    server_name example.com;
    
    root /var/www/example.com;
    index index.html;
    
    # 静态filecacheconfiguration
    location ~* \.(css|js)$ {
        expires 7d;
        add_header Cache-Control "public, max-age=604800";
        add_header ETag "$entity_tag";
        try_files $uri =404;
    }
    
    # graph片filecacheconfiguration
    location ~* \.(jpg|jpeg|png|gif|ico|svg)$ {
        expires 30d;
        add_header Cache-Control "public, max-age=2592000";
        try_files $uri =404;
    }
    
    # 字体filecacheconfiguration
    location ~* \.(woff|woff2|ttf|otf|eot)$ {
        expires 365d;
        add_header Cache-Control "public, max-age=31536000";
        try_files $uri =404;
    }
    
    location / {
        try_files $uri $uri/ =404;
    }
}

3. in 容security策略 (CSP)

server {
    listen 80;
    server_name example.com;
    
    root /var/www/example.com;
    index index.html;
    
    # 设置 in 容security策略
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';" always;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

4. 静态file访问控制

server {
    listen 80;
    server_name example.com;
    
    root /var/www/example.com;
    index index.html;
    
    # 限制访问某些静态file
    location ~* ^/private/ {
        auth_basic "Restricted Area";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
    
    # 允许跨域访问静态file
    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        add_header Access-Control-Allow-Origin *;
        try_files $uri =404;
    }
    
    location / {
        try_files $uri $uri/ =404;
    }
}

实践case: configuration high performance静态fileserver

fake设我们需要 for 一个 before 端applicationconfiguration high performance 静态fileserver, 要求:

http {
    # cachepathconfiguration
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=static_cache:10m max_size=10g inactive=60m use_temp_path=off;
    
    # Gzip压缩configuration
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    
    # Brotli压缩configuration (such as果support) 
    brotli on;
    brotli_comp_level 6;
    brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
    
    server {
        listen 80;
        server_name example.com;
        
        root /var/www/example.com;
        index index.html;
        
        # 访问log and errorlog
        access_log /var/log/nginx/example.access.log main;
        error_log /var/log/nginx/example.error.log warn;
        
        # 静态filecacheconfiguration
        location ~* \.(css|js)$ {
            expires 7d;
            add_header Cache-Control "public, max-age=604800";
            add_header Last-Modified $date_gmt;
            try_files $uri =404;
        }
        
        # graph片filecacheconfiguration
        location ~* \.(jpg|jpeg|png|gif|ico|svg)$ {
            expires 30d;
            add_header Cache-Control "public, max-age=2592000";
            try_files $uri =404;
        }
        
        # 字体filecacheconfiguration
        location ~* \.(woff|woff2|ttf|otf|eot)$ {
            expires 365d;
            add_header Cache-Control "public, max-age=31536000";
            try_files $uri =404;
        }
        
        # 禁止访问隐藏file
        location ~ /\. {
            deny all;
        }
        
        # 主requestprocessing
        location / {
            try_files $uri $uri/ =404;
            add_header X-Content-Type-Options nosniff;
            add_header X-Frame-Options SAMEORIGIN;
            add_header X-XSS-Protection "1; mode=block";
        }
    }
}

这个configurationproviding了 high performance 静态fileservice, including:

互动练习

1. Nginxserving as静态fileserver 优势 is what? ( many 选)

A. high performance
B. low memory消耗
C. flexible configuration
D. in 置cache
E. in 置压缩

2. 以 under 哪个指令用于设置静态file 根Table of Contents?

A. root
B. index
C. location
D. try_files

3. 实践练习: configuration静态fileserver

请configuration一个Nginx静态fileserver, 要求:

  • server名称 for static.example.com
  • 静态file根Table of Contents for /var/www/static
  • 启用Gzip压缩, 压缩级别 for 6
  • for CSS, JavaScriptfile设置7天cache
  • for graph片file设置30天cache
  • for 字体file设置1年cache
  • 禁止访问隐藏file

summarized and 展望

through本tutorial, 您已经Learning了Nginx静态fileservice configuration, cache策略, 压缩 and optimizationtechniques. 静态fileservice is Nginx corefunctions之一, 它可以:

in after 续 tutorialin, 我们将深入LearningNginx securityconfiguration, performanceoptimization, logmanagementetc.advanced features, helping您全面MasterNginx usingtechniques.