你所不知道的Nginx

165 阅读2分钟

安装

一些基本命令

  • 启动 start nginx
  • 关闭 nginx -s stop(快速停止nginx) 或 nginx -s quit(完整有序的停止nginx)
  • 查看运行结果 tasklist /fi "imagename eq nginx.exe"(windows)
  • 重新加载配置文件 nginx -s reload

关于配置

参考: nginx 配置文件实例

server配置

server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }
}

如果使用localhost直接发起请求,那么首先会访问到"/",结合root与index指令,首先找index.html,如果没有,就找index.htm

代理接口转发

server {
    listen       80;
    server_name  127.0.0.1

    location / {
        proxy_pass http://auth.nie.netease.com/
    }
    
    location /shop/ {
        proxy_pass http://auth.nie.netease.com/
    }
}

当直接访问127.0.0.1时,会默认访问"/",然后就会根据proxy_pass配置转发到http://auth.nie.netease.com/,如果访问127.0.0.1/shop/就会根据proxy_pass配置转发到http://auth.nie.netease.com/

在nginx中配置proxy_pass代理转发时,如果在proxy_pass后面的url加/,表示绝对根路径;如果没有/,表示相对路径,把匹配的路径部分也给代理走。

第一种:
location /proxy/ {
proxy_pass http://127.0.0.1/;
}
代理到URLhttp://127.0.0.1

第二种(相对于第一种,最后少一个 / )
location /proxy/ {
proxy_pass http://127.0.0.1;
}
代理到URLhttp://127.0.0.1/proxy

缓存

使用Nginx的http_proxy模块可以实现缓存功能。当启用缓存时,Nginx会将相应数据保存在磁盘缓存中,只要缓存数据尚未过期,就会使用缓存数据来响应客户端的请求

Nginx配置缓存

  • add_header:可以配置http头的缓存策略,资源的有效时间
语法:add_header name value
默认值:none
使用字段:http、server、location

add_header cache-control 'private, max-age=0 no-cache';
  • expires:这个指令控制是否在应答中标记一个过期时间
语法:expires [time|epoch|max|off]。
默认值:expires off。
使用字段:http、server、location。

off将禁止修改头部中的Expires和Cache-Control的。
Time控制Cache-Control的值,负数表示no-cache。
epoch将Expires头设置为1 January, 1970 00:00:01 GMT。
max将Expires头设置为31 December 2037 23:59:59 GMT,将Cache-Control最大化到10 年。

location ~* \.(jpg|jpeg|gif|bmp|png){
    expires 1d;#缓存1天
}

image.png

当第一次访问图片时,Cache-Control的max-age为86400,是一天的秒数