nginx基础(二)—— 简单应用

二、nginx基础配置

(1)错误指向一个页面

  http状态指向指定访问页面,在 /etc/nginx/conf.d/default.conf 中配置

error_page   500 502 503 504  /50x.html;
error_page   404  /404_error.html;
error_page 403 https://www.cnblogs.com/fange/;

(2)实现访问控制

location / {
       deny   123.9.51.42;    # 表示禁止哪些ip访问
       allow  45.76.202.231; # 表示只允许哪些ip访问
       deny   all;                  # 禁止所有ip访问
}

  需要注意,上述ip地址在匹配时是逐行匹配,一旦匹配到后,下面的将不再执行。

location =/user{
    allow all;
}
location =/admin{
    deny all;
}
location ~.php$ {  # 不能访问以php结尾的文件
    deny all;
}

  =表示精准匹配模式,~表示后面跟正则表达式

(3)设置虚拟主机

  在 etc/nginx/conf.d/default.conf 中配置

1 server{
2         listen 8001;
3         server_name localhost;   # 此处server_name可直接配置ip地址或域名
4         root /usr/share/nginx/html/html8001;
5         index index.html;
6 }

  编写 usr/share/nginx/html/html8001/index.html 中的html代码,使用IP:8001即可访问,(记得访问前重启nginx)

(4)反向代理

server{
        listen 80;
        server_name localhost;
        location / {
               proxy_pass https://www.cnblogs.com/fange/;
    }
}

  反向代理的其他配置项:    

  • proxy_set_header :在将客户端请求发送给后端服务器之前,更改来自客户端的请求头信息。

  • proxy_connect_timeout:配置Nginx与后端代理服务器尝试建立连接的超时时间。

  • proxy_read_timeout : 配置Nginx向后端服务器组发出read请求后,等待相应的超时时间。

  • proxy_send_timeout:配置Nginx向后端服务器组发出write请求后,等待相应的超时时间。

  • proxy_redirect :用于修改后端服务器返回的响应头中的Location和Refresh。

(5)nginx适配pc及移动端

  原理:Nginx通过内置变量$http_user_agent,可以获取到请求客户端的userAgent,就可以用户目前处于移动端还是PC端,进而展示不同的页面给用户。

  操作步骤:

    1. 在/usr/share/nginx/目录下新建两个文件夹,分别为:pc和mobile目录。

    2. 在pc和miblic目录下,新建两个index.html文件,文件写一些内容。

    3. 进入etc/nginx/conf.d目录下,修改8001.conf文件,改为下面的形式。

server{
     listen 80;
     server_name localhost;
     location / {
      root /usr/share/nginx/pc;
      if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
         root /usr/share/nginx/mobile;
      }
      index index.html;
     }
}

(6)gzip配置

  配置项:

  • gzip : 该指令用于开启或 关闭gzip模块。
  • gzip_buffers : 设置系统获取几个单位的缓存用于存储gzip的压缩结果数据流。
  • gzip_comp_level : gzip压缩比,压缩级别是1-9,1的压缩级别最低,9的压缩级别最高。压缩级别越高压缩率越大,压缩时间越长。
  • gzip_disable : 可以通过该指令对一些特定的User-Agent不使用压缩功能。
  • gzip_min_length:设置允许压缩的页面最小字节数,页面字节数从相应消息头的Content-length中进行获取。
  • gzip_http_version:识别HTTP协议版本,其值可以是1.1.或1.0.
  • gzip_proxied : 用于设置启用或禁用从代理服务器上收到相应内容gzip压缩。
  • gzip_vary : 用于在响应消息头中添加Vary:Accept-Encoding,使代理服务器根据请求头中的Accept-Encoding识别是否启用gzip压缩。

  最简配置:(在主配置文件中配置)

http {
    gzip on;
    gzip_types text/plain application/javascript text/css;
}

  配置后可使用http://tool.chinaz.com/Gzips/Default.aspx工具进行检测。

原文地址:https://www.cnblogs.com/fange/p/12366220.html