nginx 场景业务汇总 (初)

本文链接:http://www.cnblogs.com/zhenghongxin/p/8891385.html

在下面的测试中,建议每次修改nginx配置文件后,都用此命令检查一下语法是否正确:

[root@VM_71_225_centos conf]# nginx -t
nginx: the configuration file /phpstudy/server/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /phpstudy/server/nginx/conf/nginx.conf test is successful

当然,请cp一份配置,再此配置修改,不要修改生产环境的conf,可以使用此命令检查语法正确与否:

[root@VM_71_225_centos conf]# nginx -t -c /phpstudy/server/nginx/conf/nginx_bk.conf 
nginx: the configuration file /phpstudy/server/nginx/conf/nginx_bk.conf syntax is ok
nginx: configuration file /phpstudy/server/nginx/conf/nginx_bk.conf test is successful

我的nginx版本:

[root@VM_71_225_centos conf]# nginx -V
nginx version: nginx/1.4.6
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) 
TLS SNI support enabled
configure arguments: --user=www --group=www --prefix=/phpstudy/server/nginx --with-http_ssl_module --with-http_sub_module --with-http_stub_status_module --with-pcre --with-http_secure_link_module --with-http_random_index_module

(一)状态页:sub_status

 nginx 和php-fpm都内置了状态页,可以了解当前nginx的状态。

1. 启用nginx status配置

在默认主机里面加上location或者你希望能访问到的主机里面。
server {
    listen  *:80 default_server;
    server_name _;
    location /ngx_status
    {
        stub_status on;
        access_log off;
        #allow 127.0.0.1;
        #deny all;
    }
}

2. 重启nginx

请依照环境重启nginx

service nginx restart

3. 打开status页面

[root@VM_71_225_centos ~]# curl http://127.0.0.1/ngx_status
Active connections: 1 
server accepts handled requests
 629 629 687 
Reading: 0 Writing: 1 Waiting: 0 
active connections – 活跃的连接数量
server accepts handled requests — 总共处理了629个连接 , 成功创建629次握手, 总共处理了687个请求
reading — 读取客户端的连接数.
writing — 响应数据到客户端的数量
waiting — 开启 keep-alive 的情况下,这个值等于 active – (reading+writing), 意思就是 Nginx 已经处理完正在等候下一次请求指令的驻留连接.

(二)认证:auth_basic_module

 显示某些访问才被允许,其他需要密码

server{
       server_name  www.xxxx.com;
 
        index index.html index.php;
        root /data/site/www.ttlsa.com;      
 
        location /
        {
                auth_basic "nginx basic http test for xxxx.com";
                auth_basic_user_file conf/htpasswd;
                autoindex on;
        }
}

 

在conf下生成密码:(可以使用htpasswd,或者使用openssl)

# printf "ttlsa:$(openssl passwd -crypt 123456)\n" >>conf/htpasswd
# cat conf/htpasswd
ttlsa:xyJkVhXGAZ8tM

不被允许的访问,会弹出验证提示框

(三)客户端:expire 缓存

 强调客户端缓存是为了区别后面的nginx后端缓存。让客户端在访问后,短期内存在此缓存。

设置格式

expires 30s;#30秒
expires 30m;#30分钟
expires 2h;#2个小时
expires 30d;#30天

配置指令

http{
    server {
        listen 80;
        server_name test.com

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

(四)其他模块:

  • 替换网站响应内容 ngx_http_sub_module
  • 显示随机首页模块 Random Index
  • 请求限制模块 limit_conn_module 和 limit_req_module
  • 访问控制模块 access_module

(五)解决跨域访问

有两种办法,添加响应头或做反向代理,我们用第一种方法:

nginx.conf中配置增加配置
http {

  add_header Access-Control-Allow-Origin *;    # 其中*代表所有网站,也可以指定某个域名可以跨域

  add_header Access-Control-Allow-Headers X-Requested-With;

  add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

}

(六)防盗链

 在nginx.conf中找到:

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$  
{  
     expires      30d;  
}  

进行修改:

location ~* \.(gif|jpg|png|jpeg)$ {  
    expires  30d;  
        valid_referers none blocke *.xxxx.com;  
    if ($invalid_referer) {  
        rewrite ^/ http://xxx/this_is_no.jpg;  
    }  
}

valid_referers none,允许协议头为none的请求,这是在什么情况下会出现的?我们先看不能防盗链的案例:

1 直接输入网址访问该网页。
2 Javascript 打开的网址。
3 Javascript 重定向(window.location)网址。
4 使用 meta refresh 重定向的网址。
5 使用 PHP header 重定向的网址。
6 flash 中的链接。
7 浏览器未加设置或被用户修改。

上面跟none的这个设定关系很大,设定none即是允许referers为空的请求,上述的情况referers均为空。我们可以tail -f nginx 访问日志,如果我们是首次访问(直接输入网址访问该网页):

nginx访问日志中,这个refer头为空,如果不设定为none,那开发者本身打开此网址并不能拿到开发者开发的网站图片,如果在首页中点击下一个页面,看到的日志:

可以看到refer为上个网址

blocke 允许不是http的请求,和none一起造就了上面7个无法防盗链的情况

(七)搭建反向代理

这里,不详细介绍正向与反向代理的详细区别,我们可以简单的理解最大的区别在于用户目标性的多样性。反向代理是拿到其他网站数据,呈现给用户,用户始终访问的只是一个目标网站。而正向代理用户想访问一些不能访问的网址,例如google,facebook等,用户的目标性多样。更为详细的可以自行百度一下。

 简单的配置如下:

   server
        {
        listen          80;
        server_name     192.168.1.12;    //反向代理服务器IP
        location / {
                proxy_pass              http://192.168.1.10;     //web服务器IP
                proxy_redirect          off;
                proxy_set_header        X-Real-IP       $remote_addr;
                proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                }
        #error_page  404              /404.html;
  }

用户访问的是12ip,但实际上网站拿的是10的数据,对于用户来说,是不知情的。

proxy_set_header
可以更改nginx服务接收到的客户端请求的请求头信息,然后将新头发送给被代理服务器。

proxy_redirect

nginx会将host及port部分替换成自身的server_name及listen port。
注意指令转换
第一种:
location /proxy/ {
    proxy_pass http://127.0.0.1/;
}
代理到URL:http://127.0.0.1/test.html


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


第三种:
location /proxy/ {
    proxy_pass http://127.0.0.1/aaa/;
}
代理到URL:http://127.0.0.1/aaa/test.html


第四种(相对于第三种,最后少一个 / )
location /proxy/ {
    proxy_pass http://127.0.0.1/aaa;
}
代理到URL:http://127.0.0.1/aaatest.html

(八)正向代理

与反向代理非常的相似,配置举例:

user www;
worker_processes 1;
error_log /var/log/nginx/error.log debug;

events {
    use epoll;
    worker_connections 1024;
}

http {
    resolver 8.8.8.8;
    server {
        listen 8088;
        location / {
            proxy_pass http://$http_host$request_uri;
        }
    }
}

简单的理解为去用户请求的host和rui拼接而成的网站拿数据,测试的时候,需要使用浏览器代理插件测试

(九)rewrite 规则:略

(十)后端缓存:proxy_cache_path和proxy_cache

这是拿到代理后端的缓存数据,缓存于本地目录,在用户下次访问的时候,直接拿缓存访问。区别于上面的expire客户端缓存。配置如下:

proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m
use_temp_path=off;
server {
    location / {
        proxy_cache my_cache;
        proxy_pass http://my_upstream;
    }
}

proxy_cache_path命令

  • /path/to/cache/ :用于缓存的本地磁盘目录
  • levels:层次结构目录,在/path/to/cache/ 设置了一个两级层次结构的目录,大量的文件放置在单个目录中会导致文件访问缓慢,所以建议设置层次结构
  • keys_zone:  共享内存区 ,该内存区用于存储缓存键和元数据,一个1MB的内存空间可以存储大约8000个key
  • max_size : 设置缓存上限,注意:当缓存达到这个上线,处理器便调用cache manager来移除最近最少被使用的文件,这样把缓存的空间降低至这个限制之下。
  • inactive : 缓存的保持时间,如果该缓存60分钟内没有被访问,那么会被删除,如果被访问,则时间刷新重新计时。
  • use_temp_path=off : 指示nginx将在缓存这些文件时将它们写入同一个目录下

这样子当我们请求时,便可以在cache目录下看到缓存的内容。

该缓存还有很多其他功能设置:

  • 陈旧内容补缺:当代理崩溃,nginx会采取缓存内容返回,从而避免404错误页面返回。proxy_cache_use_stale error
  • 跨多硬盘分割缓存
  • 动静分离场景缓存
  • 分片请求

(十一) 更为安全的资源验证模块:secure_link

配置指令:

    location / {
        secure_link $arg_md5,$arg_expires;
        secure_link_md5 "$secure_link_expires$uri password";

        if ($secure_link = "") {
            return 403;
        }

        if ($secure_link = "0") {
            return 410;
        }
    }

(十二)Geoip读取地域信息模块

当然,我们可以在php通过一些 “纯真数据库” 等一些开源库来获取客户端地域信息(可以了解:https://www.maxmind.com/zh/home),但nginx的这个模块是在请求的开始层进行代理分发业务使用的。

配置指令:

geoip_country /etc/nginx/geoip/GeoIP.dat;
geoip_city /etc/nginx/geoip/GeoLiteCity.dat;
    location / {
        if ($geoip_country_code != CN) {  //如果不是国内IP访问,拒绝访问或者转发代理
            return 403;
        }
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

   location /myip {
        default_type text/plain;
        return 200 "$remote_addr $geoip_country_name $geoip_country_code $geoip_city";  //输出当前ip
   }

下篇待续。

posted @ 2018-04-20 16:05  hongxinerke  阅读(532)  评论(0编辑  收藏  举报