Nginx 常用配置

1. Nginx 配置虚拟主机

1.1 基于 IP 的虚拟主机

  • 修改配置文件 nginx.conf
server {
    listen 81; 
    server_name     192.168.10.9;
    root            /opt/case/wwwroot/host1;
    index           index.html index.php;
    charset         utf8;
    access_log      logs/host1.access.log;   
}   
server {
    listen 81; 
    server_name     192.168.10.109;
    root            /opt/case/wwwroot/hsot2;
    index           index.html;
    charset         utf8;
    access_log      logs/host2.access.log;
} 
  • 重启服务
[root@node10009 nginx]# ./sbin/nginx -t
nginx: the configuration file /opt/app/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/app/nginx/conf/nginx.conf test is successful
[root@node10009 nginx]# ./sbin/nginx -s reload
[root@node10009 nginx]# ss -tlnp | grep 81
LISTEN     0      128          *:81                       *:*                   users:(("nginx",pid=8486,fd=7),("nginx",pid=8435,fd=7))
[root@node10009 nginx]# 
  • 测试


    001.png
002.png

1.2 基于 主机名 的虚拟主机

-- 修改配置文件

server {
    listen 81; 
    server_name     host1.cc;
    root            /opt/case/wwwroot/host1;
    index           index.html index.php;
    charset         utf8;
    access_log      logs/host1.access.log;   
}   
server {
    listen 81; 
    server_name     host2.cc;
    root            /opt/case/wwwroot/host2;
    index           index.html;
    charset         utf8;
    access_log      logs/host2.access.log;
}   
  • 重启服务
[root@node10009 nginx]# ./sbin/nginx  -t
nginx: the configuration file /opt/app/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/app/nginx/conf/nginx.conf test is successful
[root@node10009 nginx]# ./sbin/nginx  -s reload
  • 测试


    003.png
004.png

2. nginx 配置用户认证

  • ngx_http_auth_basic_module 模块是用于访问控制的, 用户访问时只有输入了正确的用户名和密码才允许访问,
  • 默认安装Nignx 时是已安装了 该模块, 如果不需要该模块可以在编译时使用 --without_http_auth_basic_module

2.1 语法

语句: auth_basic string | off;
默认: auth_basic off;
可用段: http, server, location, limit_except
  • 在 HTTP 基本身份验证中启用了, 可以指定用户名和密码验证的文件
    auth_basic_user_file: file;
  • 用户名和密码文件格式
# comment
name1:password1
name2:password2:comment
  • 支持的密码类型:
    • 使用 crypt() 功能加密, 可以使用 htpasswd 生成, 或使用 openssl passwd 命令生成.
    • 支持基于 MD5 的密码算法(apr1)
    • 由 RFC2307 描述的. {scheme}data

2.2 测试

  • 生成验证文件
[root@node10009 nginx]# /opt/app/apache24/bin/htpasswd -c ./passwd/htpasswd testuser
New password: 
Re-type new password: 
Adding password for user testuser
[root@node10009 nginx]# 
  • 修改配置文件
server {
    listen 81;
    server_name     host2.cc;
    root            /opt/case/wwwroot/host2;
    index           index.html;
    charset         utf8;
    access_log      logs/host2.access.log;
    location / {
        auth_basic "http auth";
        auth_basic_user_file /opt/app/nginx/passwd/htpasswd;
   }
}
  • 重启服务
[root@node10009 nginx]# ./sbin/nginx -t
nginx: the configuration file /opt/app/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/app/nginx/conf/nginx.conf test is successful
[root@node10009 nginx]# ./sbin/nginx -s reload
  • 测试
005.png

3. Nginx URL重定向

  • Nginx 中重定向使用 ngx_http_rewrite_module 模块, 用于使用 PCRE正则表达式更改URI 返回重定向, 并有条件的选择配置.
  • 按照 break, if, return, rewrite 和 set顺序处理
    • 在 server 级别指定该模块的话, 会按照顺序执行.

3.1 指令以及使用

  1. break
    语法: break;
  • 用于停止当前 ngx_http_rewrite_module 指令集
  • 如果在 location 内指定了该指令, 则该 location 会处理该请求
    示例:
if($slow) {
    limit_rate 10k;
    break;
}
  1. if
  • 语法: if (condition) {...}

  • condition 是用于被判断的, 如果为true, 则指定 大括号内的指令.

  • 判断条件:

    • 变量名: 如果变量值为0, 或''(空字符串) 则为false
    • 使用 = 和 != 运算符比较变量和字符串
    • 使用 ~ (区分大小写的匹配) 和 ~* (不区分大小写) 运算符, 将变量和正则表达式进行匹配, 正则表达式可以包含 1...9 变量中的重用捕获, 反向操作符!
    • -f: 文件是否存在
    • -d: 目录是否存在
    • -e: 检查文件, 目录, 符号链接 是否存在
    • -x: 检查可执行文件
  1. return
  • 语法:

    • return code [text]
    • return code URL
    • return URL
  • 停止处理并将指定内容(code)返回给客户端, 非标准的响应码如444, 不发送响应的情况下回关闭连接.

  • 可以指定重定向的 URL, (对应的响应码 301, 302, 303, 307, 308)

  • URL 可以具有代码302 临时重定向的配置

  1. rewrite
  • 语法: rewrite regex replacement [flag]

  • 指定正则表达的请求URI 匹配, 则 URI 个根据replacement 字符串, 则rewrite 指令在其配置文件汇总出现顺序执行.

  • 可用 flag:

    • last: 停止处理当前 ngx_http_rewrite_module 指令集, 并开始搜索更改的 URI 匹配的新位置.
    • break: 和 break 指令一样, 停止处理当前的指令集
    • redirect: 返回带有 302 临时重定向, 在 替换字符串不是以 http://https:// 或者 $scheme 开头时 使用
    • permanent: 返回301 代码, 永久重定向
  • 示例:

server {
    rewrite ^(/download/.*)/media/(.*)\..*$  $1/mp3/$2.mp3 break;
    rewrite ^(/download/.*)/audio/(.*)\..*$  $1/mp3/$2.ra break;
}

location /download/ {
    rewrite ^(/download/.*)/media/(.*)\..*$  $1/mp3/$2.mp3 break;
    rewrite ^(/download/.*)/audio/(.*)\..*$  $1/mp3/$2.ra break;
}
  • 需要注意的是如果 rewrite 写在了 location /download/{} 段中, 则标志位 应当为 break 而不可写成 last, 否则会循环10次后 返回500

3.2 使用示例

  • 修改配置文件
server {
    listen 80; 
    server_name     host2.cc;
    # root            /opt/case/wwwroot/host2;
    # index           index.html;
    # charset         utf8;
    access_log      logs/host2.access.log;
    if ($host = 'host2.cc') {
        rewrite (.*) http://host1.cc/$1 permanent;
    }   
}   
  • 重启服务
[root@node10009 nginx]# ./sbin/nginx -t
nginx: the configuration file /opt/app/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /opt/app/nginx/conf/nginx.conf test is successful
[root@node10009 nginx]# ./sbin/nginx -s reload
[root@node10009 nginx]# 
  • 测试
006.png

4. Nginx 访问日志

4.1 访问日志介绍

  • Nginx 会把每个用户访问信息 记录到日志文件中,
  • 日志模块 ngx_http_log_module

4.2 访问日志参数

  • log_format: 用来设置日志记录格式,( 可以自定义多种日志记录格式, 取不同名字)
  • access_log: 用来指定日志记录的文件,

4.1 Logforamt 配置

  • 默认值:
log_format  mian    '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_byte_sent "$http_referer"'
                    '"$http_user_agent" "$http_x_forded_for"'
  • logFormat 可用参数
    log_format      <NAME>      <String>
    关键字          格式名        日志格式

$remote_addr:   记录访问网站的客户端地址
$remote_user    客户端使用的用户名
$time_local     访问时间
$request        用户的 http 请求头信息(http协议版本, 请求URI, 请求方式)
$status         http 响应状态码, (200, 301, 304, 404...)
$body_bytes_send    服务器发送给客户端的 字节数
$http_referer       记录该请求的上一个跳转的地址, (可以根据该参数设置防盗链)
$http_user_agent    记录客户端信息, (如Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36)
$ http_x_forwarded_for  当前端有代理服务器时,在web 节点设置记录客户端地址的配置, 参数用于记录 客户端实际地址.

4.1 access_log 配置

  • access_log 语法:
access_log  logs/access.log     main;

access_log 其他语法:

access_log  off;        # 不记录访问日志
access_log  PATH  [FORAMT [buffer=size [flush=time] [if=condition]]];
access_log  PATH  FORMAT gzip[=level] [buffer=size] [flush=time] [if=condition];
access_log  syslog:server=address[,parameter=value] [format [if=condition]];
---------- 
# 参数说明
buffer=size         # 记录访问日志的缓冲区大小.
flush=time          # 将缓冲区刷入磁盘的时间

4.2 logrotate 切割日志

logrotate 工具是linux 系统中常用的日志文件管理工具,常用于切割日志, 删除旧日志, 创建新日志文件.

  1. loggrotate 配置文件
    logrotate 有两个配置文件位置.
  • /etc/logrotate.conf
  • /etcv/logrotate.d/*.conf
  1. logrotate 命令
  • 命令格式: logrotate [OPTION..] <configfile>
  • 命令选项:
-d      --debug debug 模式, 测试配置文件是否有错误
-f      --force  轻质转储文件     
-m      --mail=command 压缩日之后发送的邮箱
-s      --state=statefile   使用指定状态的 文件
-v      --verbose   显示转储过程
  1. 日志切割
  • 配置文件示例:
/opt/app/nginx/logs/*log {
    create 0644 nginx nginx
    daily
    rotate 10
    missingok
    notifempty
    compress
    sharedscripts
    postrotate
        /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}
  • 配置解析
/opt/app/nginx/logs/*log {      # 日志文件位置
    create 0644 nginx nginx     # 创建新日志时的权限, 
    daily                       # 日志按日切割, 可以选 monthly, weekly, yearly
    rotate 10                   # 保留的归档数量, 这里是保留10个归档.
    missingok                   # 日志轮询时会忽略错误, 
    notifempty                  # 如果日志为空, 则不轮询 
    compress                    # 轮询结束会使用 gzip 压缩
    sharedscripts               # 运行posttrotate 脚本, 作用是在所有日志切割后 统一执行一次, 如果不配置, 则会在每个日志后执行一次 
    postrotate                  # 在logrotate 转储前执行的脚本, 必须是独立运行的
        /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript                   # 结束后执行
}
--- 可选其他配置项
nocompress          # 不使用压缩
copytruncate        # 用在打开中的日志, 把当前日志备份并截断, 就是先拷贝, 在清空 可能会有日志丢失

  1. 测试
[root@node10009 nginx]# ls logs
access.log  error.log  host1.access.log  host2.access.log  nginx.pid
[root@node10009 nginx]# logrotate -f /etc/logrotate.d/nginx 
[root@node10009 nginx]# ls logs
access.log       error.log       host1.access.log       host2.access.log       nginx.pid
access.log.1.gz  error.log.1.gz  host1.access.log.1.gz  host2.access.log.1.gz
[root@node10009 nginx]# du -h ./logs/*
0   ./logs/access.log
4.0K    ./logs/access.log.1.gz
0   ./logs/error.log
4.0K    ./logs/error.log.1.gz
0   ./logs/host1.access.log
4.0K    ./logs/host1.access.log.1.gz
0   ./logs/host2.access.log
4.0K    ./logs/host2.access.log.1.gz
4.0K    ./logs/nginx.pid
[root@node10009 nginx]# 
  1. 自动轮询日志文件
  • 将轮询日志的命令写入crontab 中,
# crontab -l
 30 0 * * * /usr/sbin/logrotate -f /etc/logrotate.d/nginx

4.3 静态文件不记录日志, 并设置过期时间

  1. 配置文件
server {
    ...
    location ~ .*\.(jpg|png|gif|jpeg)$ {
        expires 5d; 
        access_log off;
    }   
    ...
}
------------------
expires     设置客户端缓存的过期时间
access_log off  不记录日志 
  1. 测试
[root@node10009 nginx]# curl host1.cc/1.png -I
HTTP/1.1 200 OK
Server: nginx/1.14.0
Date: Tue, 11 Dec 2018 17:30:52 GMT
Content-Type: image/png
Content-Length: 0
Last-Modified: Tue, 11 Dec 2018 17:30:50 GMT
Connection: keep-alive
ETag: "5c0ff44a-0"
Expires: Sun, 16 Dec 2018 17:30:52 GMT
Cache-Control: max-age=432000
Accept-Ranges: bytes

[root@node10009 nginx]# tail -n2 ./logs/host1.access.log
192.168.10.9 - - [12/Dec/2018:01:30:11 +0800] "HEAD / HTTP/1.1" 200 0 "-" "curl/7.29.0"
192.168.10.9 - - [12/Dec/2018:01:30:21 +0800] "HEAD /1.pnga HTTP/1.1" 404 0 "-" "curl/7.29.0"
[root@node10009 nginx]# 

5. Nginx 防盗链设置

  1. valid_referers 说明
  • 语法: valid_referers none|blocked|server_names|string ...
  • 参数
none:  
    表示请求的 http_referer 字段为空
blocked:
    referer 字段出现在请求字段中, 但是已被防火墙删除了, 这些值不是 http:// 或 https:// 开头的
server_names
    Referer 请求字段头是一个指定的服务器名.
string:
    任意字符串,指定的
正则表达式
  • 内嵌的变量$invalid_referer
    • 如果 上面的 valid_referers 匹配成功, 则该变量为 0, 不匹配则为 1
  1. 针对文件设置防盗链
location ~ .*\.(png,gif)$ {
    valid_referers none blocked www.host1.com  baidu.com;
    if ($invalid_referer) {
        return 403;
    }
}
  1. 针对指定目录设置防盗链
location /images/ {
    vaid_referers none blocked www.host1.cc host1.cc;
    if ($invalid_referer){
        return 403;
    }
}

6. Nginx 访问控制

  • nginx 访问控制使用的模块是 ngx_http_access_module
  • 会从上往下 按顺序检查 配置, 直到有满足要求的

6.1 allow指令

  • allow 用于控制允许访问指定的网址 或地址,如果指定了 uinx: 则访问所有unix 套接字
  • 语法: allow address|CIDR|unx:|all

6.2 deny

  • 用于控制拒绝访问的网络或地址,
    语法: ddeny address|CIDR|uinx:|all

END

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容