if指令
可使用的全局变量
变量名称 | 变量说明 |
$args | 这个变量等于请求行中的参数,同$query_string |
$content_length | 请求头中的Content-length字段 |
$content_type | 请求头中的Content-Type字段请求头中的Content-Type字段 |
$document_root | 当前请求在root指令中指定的值 |
$host | 请求主机字段 |
$http_user_agent | 客户端agent信息 |
$http_cookie | 客户端cookie信息 |
$limit_rate | 速率 |
$request_method | 客户端请求的动作 |
$remote_addr | 客户端的IP地址 |
$remote_port | 客户端的端口 |
$remote_user | 已经经过Auth Basic Module验证的用户名 |
$request_filename | 请求文件路径 |
$scheme | HTTP方法 |
$server_protocol | 请求协议 |
$server_addr | 服务器地址 |
$server_name | 服务器名称 |
$server_port | 请求到达服务器的端口号 |
$request_uri | 包含请求参数的原始URI |
$uri | 不带请求参数的当前URI |
$document_uri | 不带请求参数的当前URI |
例子
hapa.cc==>hapa.com
if ($host ~* hapa.cc ) {
rewrite .* http://hapa.com permanent;
}
set指令
*.hapa.cc==>hapa.cc/*
if ( $host ~* "^(.*)\.hapa\.cc$" ) {
set $user $1;
rewrite .* http://hapa.cc/$user permanent;
}
}
return 指令
80==>443
server {
listen 80;
server_name hapa.cc;
access_log /var/log/nginx/http_access.log main;
return 301 https://hapa.cc$request_uri;
}
location 指令
= 表示精确匹配,优先级也是最高的
^~ 表示 url 以某个常规字符串开头,理解为匹配url路径即可
~ 表示区分大小写的正则匹配
~* 表示不区分大小写的正则匹配
!~ 表示区分大小写不匹配的正则
!~* 表示不区分大小写不匹配的正则
/ 通用匹配,任何请求都会匹配到
@ 内部服务跳转
定义日志格式
log_format main '$http_x_real_ip $http_host [$time_local] "$request"
$request_length '
'$status $body_bytes_sent $request_time "$http_referer" '
'"$http_user_agent" $remote_addr ';
切割日志实例
#!/bin/bash
# Nginx 日志存放目录
LOGDIR="/data0/www/logs"
# 一定要设置Nginx 的 access log 日志文件后缀名都为 -access_log
LOGSUFFIXA="*-access_log"
# 归档日志存放的目录
LOGARCHIVE="/data0/www/logs/archives"
# Nginx 的Pid 文件
PID="/usr/local/nginx/logs/nginx.pid"
# 删除 30天以前的日志
find $LOGARCHIVE -type f -atime +30 -exec rm -f {} \; > /dev/null 2>&1
# 删除空目录
find $LOGARCHIVE -type d -empty -exec rmdir {} \; >/dev/null 2>&1
# 获取前一天的时间
DATE=`date --date="LAST DAY" "+%y%m%d"`
# 创建前一天归档日志目录
LOGARCHIVE="$LOGARCHIVE/$DATE"
test -d $LOGARCHIVE || mkdir -p $LOGARCHIVE
cd $LOGDIR
for FILE in *$LOGSUFFIXA*; do
mv $FILE $LOGARCHIVE
done
# 发送 USR1 信号给Nginx, 让Nginx 重新打开日志文件。
kill -USR1 `cat ${PID}