Nginx笔记

nginx状态信息模块

状态信息模块由ngx_http_stub_status_module模块,记录基本访问状态信息。编译时候需要增加此模块

[root@centos vhost]# cat status.conf 
server{
	listen 80;
	server_name status.suixin.com;
	location / {
		stub_status on;   #打开状态信息开关
		access_log	off;
	}

}

绑定hosts访问status.suixin.com,结果如下:

Active connections: 2   <--表示正处理的活动链接有2个
server accepts handled requests
 2 2 1 
Reading: 0 Writing: 1 Waiting: 1 

第一个server表示nginx启动到现在共处理了2个链接
第二个accepts表示nginx启动到现在共成功创建了2次握手
请求丢失数=(握手数-连接数),可以看出,本次显示没有丢失请求
第三个为handled requests,表示总共处理了1次请求

日志模块

日志模块是由ngx_http_log_modeule模块负责

nginx访问日志主要由两个参数控制

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

2.1 nginx日志格式中的参数配置

http{
    include mime.types;
    default_type application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"'
    access_log on;
    access_log logs/access_www.log main;    #也可以选择写到server标签里面

$remote_addr:记录访问网站的客户端地址
$remote_user :远程客户端的用户名称
$time_local:记录访问时间和时区
$request:用户的htto请求起始行信息
$status:http状态码,记录请求返回的状态
$body_bytes_sent:服务器发送给客户端的相应bode字节数
$http_referer:记录此次请求是从哪个链接访问过来的,根据referer进行防盗链设置
$http_user_agent:记录客户端访问信息,例如:浏览器、手机客户端等
$http_x_forwarded_for:当前端有代理服务器时,设置web节点记录客户端地址的配置,前提是代理服务器也进行了相关的x_forwarded_for设置

没有特殊需求,采用默认的配置即可

也可以在记录日志参数中加上buffer和flush选项,提高在高并发场景下提升网站的访问性能

access_log logs/access_www.log main gzip buffer=32k flush=5s;

2.2 nginx访问日志切割-shell脚本方式

默认情况nginx会把所有访问日志生成到一个指定的访问日志文件acess.log里,时间长导致日志很大,不利于日志的分析和处理,因此,有必要对nginx日志按天或按小时进行切割,这里采取按天切割方法。

具体切割脚本如下:

[root@centos logs]# cat /shell/cut_nginx_log.sh 
#!/bin/sh
Dateformat=`date +%Y%m%d`
Basedir="/opt/nginx/logs"
Logname="access_www"
[ -d $Basedir ] && cd $Basedir ||exit 1
[ -f $Logname.log ] || exit 1
/bin/mv $Logname.log	${Dateformat}_${Logname}.log
kill -USR1 `cat /opt/nginx/logs/nginx.pid`


[root@centos logs]# crontab -l
00 00 * * *	/bin/sh /shell/cut_nginx_log.sh >/dev/null 2>&1

2.2 nginx访问日志切割-logrotate方式

linux自带的日志轮询工具logrotate

logrotate的配置文件:/etc/logrotate.conf /etc/logrotate.d/*

logrotate的默认计划任务:/etc/anacrontab

logrotate的配置文件

~]# cat /etc/logrotate.d/nginx
/opt/nginx1.13/logs/*.log {
        daily  指定转储周期为每天
        rotate 7   保留7个备份
        create     由于日志文件被重命名,因此新建一个新的来继续存储
        missingok    如果日志丢失,不报错继续滚动下一日志
        notifempty    如果日志为空,不轮询
        dateext                使用当期日期作为命名格式
        sharedscripts    所有日志轮询后执行一次postrotate脚本
        postrotate
                /bin/kill -USR1 $(cat /opt/nginx/run/nginx.pid 2>/dev/null) 2>/dev/null || :
        endscript
}

logrostate计划任务

~]# cat /etc/anacrontab
# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=9      延迟时间
# the jobs will be started during the following hours only
START_HOURS_RANGE=23-24    这里是日志切割时间,即在23-24点间执行

#period in days   delay in minutes   job-identifier   command
1	50	cron.daily		nice run-parts /etc/cron.daily   50也是延迟时间,即改任务在23点59分执行
7	25	cron.weekly		nice run-parts /etc/cron.weekly
@monthly 45	cron.monthly		nice run-parts /etc/cron.monthly

nginx location

location语法:

location [ = | ~ | -* | ^~ ] uri {

}
location [ =丨*丨^~丨@ ] uri
指令 匹配标识 匹配的网址 配置uri后要执行的配置段

匹配这两种特殊字符“”或“*”的区别为:“”用于区分大小写的匹配;"*"用于不区分大小写的匹配。

还可以用逻辑操作符"!"对上面的匹配取反,即"!~" "!~*"

"^~"的做用是在进行常规的字符串匹配检查后,不做正则表达式的检查,即如果最明确的那个字符串匹配的location匹配中location配置中有此前缀,那么不做正则表达式的检查

nginx rewrite

rewrite是实现URL重写的关键指令,根据regex(正则表达式)部分的内容,重定向到相关域名,结尾是flag标记

rewrite ^/(.*)  http://www.suixinl.top/$1 permanent;
域名中的$1是前面括号里面的内容,结尾permanent是永久301重定向标记。

regex常用正则表达式字符

字符 描述
\ 将后面接着的字符标记为一个特殊字符或一个原义字符或一个向后引用。例如,"\n"匹配一个换行符,序列"\"和"$"则匹配"$"
^ 匹配输入字符串的起始位置,如果设置RegExp对象的Multiline属性,^也匹配"\n"或"r"之后的位置
$ 匹配输入字符串的结束位置,如果设置了RegExp对象的Multilines属性,$也匹配"\n"或"\r"之前的位置
  • | 匹配前面的字符零次或多次,例如,ol能匹配"o"及"olll",等价于
  • | 匹配前面的字符一次或多次,例如,"ol+"能匹配"ol" 及"oll",但不能匹配"o",.+等价于{1,}
    ? | 匹配前面的字符零次或一次,例如, "do(es)?"可以匹配"do"或"does"中的"do", .?等价于{0,1};当该字符紧跟任何一个其他限制符(*,+?,{n},{n,m})的后面,匹配的是非贪婪模式的,例如,对于字符串"oooo","0+?"将匹配单个"o",而"o+"将匹配所有"o"
    . | 匹配除了"\n"之外的任何单个字符,要匹配包括"\n"在内的任何字符,请使用"[.\n]"这样的模式
    (pattern) | 匹配括号内的pattern,并可以在后面获取对应的匹配,常用$0...$9属性获取小括号中的匹配内容,要匹配圆括号字符,请使用"(" 或 ")"

rewrite指令最后一项参数flag标记说明

flag标记符号 说明
last 本条规则匹配完成后,继续向下匹配新的locationURI规则
break 本条规则匹配完成即终止,不在匹配后面的任何规则
redirect 返回302临时重定向,浏览器会显示跳转后的URL地址
permanent 返回301永久重定向,浏览器地址栏会显示跳转后的URL地址

注释:
1.在以上flag标记中,last和break用来实现URI重写,浏览器的URI地址不变

2.redirect和permanent用来实现URL跳转,浏览器显示跳转后的URL地址

3.last和break的差别:使用alias指令必须用last标记,使用proxy_pass指令时要使用break标记。

4.在根location(即location/{...})中或server{...}标签中编写的rewrite规则,建议使用last标记,而在普通的location(例location/oldboy/{......})或if{...}中编写rewrite规则,则建议使用break标记。

nginx访问认证

需求:为网站设置访问账号和密码权限,应用在企业内部人员访问的地址上,例如:企业网站后台、mysql客户端phpmyadmin、企业内部的CRM、WIKI网站平台等。
示例:

location / {
    auth_basic      "closed site";   #认证提示字符串
    auth_basic_user_file    conf/htpasswd;    #认证密码文件
}

[root@centos vhost]# yum -y install httpd
[root@centos vhost]# htpasswd -bc /opt/nginx/conf/htpasswd suixin 123456
[root@centos vhost]# chmod 400 /opt/nginx/conf/htpasswd
[root@centos vhost]# chown www.www /opt/nginx/conf/htpasswd
[root@centos vhost]# cat /opt/nginx/conf/htpasswd 
suixin:Ot08TczOnIiXg    <--加密过的
[root@centos vhost]# /opt/nginx/sbin/nginx -s reload

限制用户上传部分文件

location ~ ^/images/.*\.(php|php5|sh|pl|py)$
        {
            deny all;
        }
location ~ ^/static/.*\.(php|php5|sh|pl|py)$
        {
            deny all;
        }
location ~* ^/data/(attachment|avatar)/.*\.(php|php5)$
        {
            deny all;
        }

对于上述目录的限制必须卸载下面nginx处理PHP配置的前面

location ~ .*\.(php|php5)?$
{
    fastcgi_pass    127.0.0.1:9000;
    fastcgi_index   index.php;
    include     fcgi.conf;
}

配置nginx,禁止非法域名解析

问题:禁止用户IP访问网站

方法1:让使用IP访问网站,或者恶意解析域名的用户,收到501错误

server{
    listen  80  default_server;
    server_name _;
    return 501
}

方法2:通过301跳转到主页

server{
    listen 80 default_server;
    server_name _;
    rewrite ^(.*)   http://suixinl.top/$1   permanent;
}

方法3:发现某域名恶意解析到公司服务器IP,在server标签添加以下

if ($host   !~  ^www/.suixinl/.top$){
    rewrite ^(.*)   http://suixinl.top$1    permanent;
}

nginx防盗链实战(两种方法)

(1)利用referer,针对拓展名rewrite重定向(放到server标签中)

location ~* \/(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$    {
    valid_referer   none    blocked *.suixinl.top   suixinl.top;
if  ($invalid_referer)  {
    rewrite ^/  http://www.suixinl.top/img/nolink.jpg
    }
}

(2)利用referer,针对站点目录过滤返回错误码

location /images    {
    root    html/www;
    valid_referer   none    blocked *.suixinl.top   suixinl.top;
if ($invalid_referer) {
    return 403;
    }
}

http_proxy_module模块

此模块可以将请求转发到另一台服务器
案例:
将配置URI为name的请求抛给http://127.0.0.1/remote/

location /name/ {
    proxt_pass http://127.0.0.1/remote/;
}

http proxy模块相关参数

proxy_set_header:设置http请求header项传给后端服务器节点,例如可实现让代理后端的服务器节点获取访问客户端用户的真实IP地址

client_body_buffer_size:用于制定客户端请求主体缓冲区大小

proxy_connect_timeout:表示反向代理与后端节点服务器链接的超时时间

proxy_send_timeout:表示代理后端服务器数据回传时间

proxy_read_timeout:nginx从代理的后端服务器获取信息的时间

proxy_buffer_size:设置缓冲区大小

proxy_buffers:设置缓冲区的数量和大小

proxy_busy_buffers_size:设置系统很忙时可以使用的proxy_buffer大小

proxy_temp_file_write_size:指定proxy缓存临时文件的大小

问题1:反向代理在节点机跳转到真实服务器时,真实服务器的nginx日志看到的是节点机的ip,此时,可在server标签的location下做如下添加
解决方法:

proxy_set_header X-Forwarded-For $remote-addr;
#这是反向代理时,节点服务器获取用户真实IP的必要功能
#这里虽然代理已经配好了,但是日志格式要加上$http_x_forwarded_for

问题2:在代理向后端服务器发送请求头中没有host信息,后端服务器配置多个虚拟主机,代理识别不出,默认交给第一个虚拟主机,因此要在代理的发送那个请求头加入host字段信息,这是节点服务器多虚拟主机时的关键配置,此时,可在server标签的location下做如下添加

解决方法:

proxy_set_header Host   $host;

nginx配置文件如下:

user  www www;
worker_processes 4;
error_log  /opt/nginx/logs/nginx_error.log  crit;
pid   /opt/nginx/nginx.pid;
worker_rlimit_nofile 65535;     #worker最大打开文件数

events
{
    use epoll;
    worker_connections 65535;    #worker最大连接数
}

http{
    include mime.types;
    default_type application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent"'
    access_log on;
    access_log logs/access_www.log main gzip buffer=32k flush=5s;
    error_log /opt/nginx/logs/error.log;
    
    server_names_hash_bucket_size 128;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 8m;        #上传文件的大小限制
    open_file_cache max=102400 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 1;
    sendfile on;            #高效文件传输模式
    tcp_nopush on;
    keepalive_timeout 60;       #客户端连接保持会话超时时间为60s
    tcp_nodelay on;    #提高I/O性能

    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 32k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xhtml+xml text/xml application/xml application/xml+rss;
    gzip_vary on;

    include vhost/*.conf;
}

fastcgi以下参数详细可以参考老男孩web集群一书的330页

fastcgi_connect_timeout
表示nginx服务器和后端FastCGI服务器连接的超时时间,默认60s。

fastcgi_send_timeout 300;
nginx允许FastCGI服务端返回数据的超时时间

fastcgi_read_timeout 300;
nginx从FastCGI服务端读取响应时间的超时时间

fastcgi_buffer_size 64k;
nginx FastCGI的缓冲区大小参数

fastcgi_buffers 4 64k;
设定用来读取FastCGI服务端手段哦的响应时间的缓冲区大小和缓冲区数量。

fastcgi_busy_buffers_size 128k;
用于设置系统很忙时可以使用proxy_buffers大小

fastcgi_temp_file_write_size 128k;
FastCGI临时文件大小
posted @   彬彬l  阅读(48)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示