JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

nginx-3-默认网站和防盗链

wys521 2024-09-18 03:01:55 精选教程 25 ℃ 0 评论

四 默认网站及设置


1 默认网站

server {
    listen       80;

    server_name  localhost;

    location / {

        root   html;

        index  index.html index.htm;

        #支持目录浏览
         autoindex  on;

    }

    error_page   500 502 503 504  /50x.html;

    location = /50x.html {

        root   html;

    }

}

2 访问控制

[root@localhost ~]# mkdir /usr/local/nginx/html/a
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
location /a {
    autoindex on;
    deny 192.168.11.116;
    allow all;
    #基于客户端IP做过滤,符合条件的允许访问,不符合的禁止访问
    }
[root@localhost ~]# killall  -s HUP nginx

3 登陆验证

[root@localhost ~]# mkdir /usr/local/nginx/html/c
[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
location /c {
    auth_basic "登陆验证";
    auth_basic_user_file /etc/nginx/htpasswd;

}
[root@localhost ~]# killall  -s HUP nginx

4 日志管理

Nginx访问日志主要有两个参数控制

log_format #用来定义记录日志的格式(可以定义多种日志格式,取不同名字即可)

access_log #用来指定日志文件的路径及使用的何种日志格式记录日志

access_log logs/access.log main;

log_format格式变量:
    $remote_addr  #记录访问网站的客户端地址
    $remote_user  #远程客户端用户名
    $time_local  #记录访问时间与时区
    $request  #用户的http请求起始行信息
    $status  #http状态码,记录请求返回的状态码,例如:200、301、404等
    $body_bytes_sent  #服务器发送给客户端的响应body字节数
    $http_referer  #记录此次请求是从哪个连接访问过来的,可以根据该参数进行防盗链设置。
    $http_user_agent  #记录客户端访问信息,例如:浏览器、手机客户端等
    $http_x_forwarded_for  #当前端有代理服务器时,设置web节点记录客户端地址的配置,此参数生效的前提是代理服务器也要进行相关的x_forwarded_for设置

自定义一个json格式的访问日志

log_format main_json '{
        "@timestamp":"$time_local",
        "client_ip":"$remote_addr",
        "request":"$request",
        "status":"$status",
        "bytes":"$body_bytes_sent",
        "x_forwarded":"$http_x_forwarded_for",
        "referer":"$http_referer"
                                            }';
    access_log logs/access_json.log main_json;

#重新启动nginx服务查看访问日志
[root@localhost~]# tail -f /usr/local/nginx/logs/access_json.log

5 防盗链

[root@localhost html]# vim /usr/local/nginx/conf/nginx.conf
location / {
            root   html;
            index  index.html index.htm;
        }
        #定义访问资源为图片类型的
location ~* \.(gif|jpg|png|bmp)$ {
                #定义白名单  none代表直接访问的,blocked表示被防火墙标记过的请求最后一个是网址
           valid_referers none blocked *.baidu.com;
                 #如果不在白名单中则返回403
                 if ($invalid_referer) {
                        return 403;
                                        }
        }
[root@localhost ~]# killall  -s HUP nginx       
#在另外一台主机写一个盗链测试页面
dnf install httpd -y
vim /var/www/html/index.html
<html>
        <head>
                <title>ce shi</title>
                <body>
                        <a href="http://192.168.11.16/1.png">daolian</a>
                </body>
        </head>
</html>

systemctl restart httpd

总结

nginx的默认网站

访问控制

登录验证

日志管理

防盗链

重点:nginx的基本功能如何实现

难点:日志格式的定义和防盗链的实现



3分钟了解计算机发展历史-组团学

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表