搭建nginx静态资源站

搭建静态资源站包括以下几部分:

  1. root指令与alias指令的区别
  2. 使用gzip压缩资源
  3. 如何访问指定目录下的全部资源文件
  4. 如何限制访问流量
  5. 如何自定义log日志

  root指令与alias指令的区别

我们的网站静态资源放到  /home/wwwroot/demo 目录下

root@2a33e33fa785:/home/wwwroot/demo# ls
about.html  about1.html  css  fonts  gallery.html  images  index.html  js  typography.html

nginx.conf 文件

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location /demo/ {
            root   /home/wwwroot;
       #alias /home/wwwroot/demo/; } } }

上面的配置文件中 root和alias 指令配置完之后实现的效果是一样的,其实用的区别在于:

  • 使用root指令时,访问 http://ip:端口号/demo/index.html 时,nginx回去root 指定的目录下按照url地址来寻找index.html文件
  • 使用 alias 指令就相当于为 /demo/ 起了个别名 /demo/ 与 alias 指定的目录是等同的所以当同样访问 http://ip:端口号/demo/index.html 时,nginx 获取 alias 指定的目录下寻找 index.html 文件

  使用gzip压缩

#开启gzip
gzip  on;   
#低于1kb的资源不压缩
gzip_min_length 1k; 
#压缩级别【1-9】,越大压缩率越高,同时消耗cpu资源也越多,建议设置在4左右。
gzip_comp_level 3; 
#需要压缩哪些响应类型的资源,多个空格隔开。不建议压缩图片,下面会讲为什么。
gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;  

使用前 index.html 的请求大小

开启gzip之后

  访问指定目录下的全部资源文件

在 server 或者 http 或者 location 指令中 加入  autoindex on;  指令

  限制访问流量

添加  set $limit_rate 1k 限制请求每秒只能传输1kB数据,这时我们访问页面会明显感觉到很慢

  设置log日志

设置日志格式     log_format 模板名称 日志中包含的内容  注意:模板中所保存的内容可以是nginx模块及第三方模块提供的任意参数内容,例如 这里 提供的变量都可以存储起来

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 日志路径 模板名称; 

access_log  logs/host.access.log  main;

最后是完整的配置文件

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    sendfile        on;

    keepalive_timeout  65;

    gzip  on;
    gzip_min_length 1k;
    gzip_comp_level 3;
    gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;

    server {
        listen       80;
        server_name  localhost;

        access_log  logs/host.access.log  main;

        location / {
            root   /home/wwwroot/demo/;
            autoindex on;
            set $limit_rate 1k;
        }

    }

}
posted @ 2019-07-23 22:20  GPHPER  阅读(3461)  评论(0编辑  收藏  举报
TOP