使用Nginx搭建静态资源WEB服务器

使用Nginx搭建静态资源WEB服务器

一、下载一个静态WEB资源示例

从这个网站中可以下载dclib的静态资源示例:

https://sourceforge.net/projects/dclib/

二、将静态资源放到nginx目录下

/dev/servers/nginx/dlib

$tree dlib | more
dlib
├── CMakeLists.txt.html
├── algs.h.html
├── all
│   └── source.cpp.html
├── any
│   ├── any.h.html
│   ├── any_abstract.h.html
│   ├── any_decision_function.h.html
│   ├── any_decision_function_abstract.h.html
│   ├── any_function.h.html
│   ├── any_function_abstract.h.html
│   ├── any_function_impl.h.html
│   ├── any_function_impl2.h.html
│   ├── any_trainer.h.html
│   └── any_trainer_abstract.h.html
├── any.h.html
├── appveyor
......

三、配置Nginx

  • 配置需要监听的端口

  • 配置一个location

    配置的时候一定要注意语法问题,使用“;”结尾

    可以使用./sbin/nginx -t 检查语法是否有问题

        server {
            listen       8088;
            server_name  localhost;
    
            #charset koi8-r;
    
            #access_log  logs/host.access.log  main;
    
            location / {
                alias  dlib/;
                #root   html;
                #index  index.html index.htm;
            }
    

    所有的访问请求都访问dlib下面的文件,location后面的/表示所有的请求。

    需要指定url的后缀与文件名的后缀一一对应,这个时候有两种用法:

    (1)使用root

    使用root有一个问题,它会将Url的路径带到目录中来。所以一般使用alias

    (2)使用alias

    这里的含义是,location后面的路径与 dlib目录的路径一一对应。

    四、启动nginx

    cd /dev/servers/nginx/sbin
    ./nginx
    

    五、访问

    http://localhost:8088/

    六、其他功能

    6.1 GZIP压缩

    这时候通过查看抓包的大小,发现所抓包的大小和文件大小一致。

    所有的文本可以做GZIP压缩的,压缩之后的大小会大幅度减少。

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zUkCPdK2-1589325336741)(photos/01gzip压缩之前.png)]

    打开gzip压缩:

        # 开启gzip压缩
        gzip  on;
        # 小于 1字节 的不压缩
        gzip_min_length 1;
        # gzip 压缩的级别
        gzip_comp_level 2;
        # 对哪些文件进行压缩
        gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
    
        server {
            listen       8088;
            server_name  localhost;
    ......
    

    重启nginx:

    ./sbin/nginx -s reload

    再次访问:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LYdrDbcU-1589325336744)(photos/02gzip压缩之后.png)]

6.2 使用 autoindex 来共享资源文件

这个访问“/”结尾的URL,可以在页面上展示目录结构:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m4ruXxZd-1589325336746)(photos/03autoindex示例.png)]

6.3 使用$limit_rate限制访问速度

http://nginx.org/en/docs/http/ngx_http_core_module.html#limit_rate


        location / {
            alias  dlib/;
            autoindex on;
            set $limit_rate 1k;
            #root   html;
            #index  index.html index.htm;
        }

再次访问首页,发现访问速度非常慢

6.4 记录access日志

  • 定义日志格式
  • 对日志格式进行命名
  • 设置日志记录在在哪
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值