linux高阶-Nginx服务(五)-核心配置详解

Nginx核心配置详解

全局配置

user  nginx nginx;                 # 启动Nginx⼯作进程的⽤⼾和组
worker_processes  [number | auto]; # 启动Nginx⼯作进程的数量
worker_cpu_affinity 00000001 00000010 00000100 00001000;
# 将Nginx⼯作进程绑定到指定的CPU核⼼,默认Nginx是不进⾏进程绑定的,绑定并不是意味着当前nginx进程独
# 占以⼀核⼼CPU,但是可以保证此进程不会运⾏在其他核⼼上,这就极⼤减少了nginx的⼯作进程在不同的cpu核
# ⼼上的来回跳转,减少了CPU对进程的资源分配与回收以及内存管理等,因此可以有效的提升nginx服务器的性
# 能。 此处CPU有四颗核心。也可写成:
worker_cpu_affinity 0001 0010 0100 1000;


# 错误⽇志记录配置,语法:error_log file  [debug | info | notice | warn | error | crit | alert | emerg]
# error_log  logs/error.log;
# error_log  logs/error.log  notice;
error_log  /apps/nginx/logs/error.log error;

# pid⽂件保存路径
pid        /apps/nginx/logs/nginx.pid;

worker_priority 0; # ⼯作进程nice值,-20~19
worker_rlimit_nofile 65536; # 这个数字包括Nginx的所有连接(例如与代理服务器的连接等),⽽不仅仅是与
                            # 客⼾端的连接,另⼀个考虑因素是实际的并发连接数不能超过系统级别的最⼤打开⽂件数的限制.
[root@s2 ~]# watch -n1  'ps -axo pid,cmd,nice | grep nginx' #验证进程优先级

daemon off;  # 前台运⾏Nginx服务⽤于测试、docker等环境。
master_process off|on; #是否开启Nginx的master-woker⼯作模式,仅⽤于开发调试场景。

events { # 事件模型配置参数
    worker_connections  65536;  # 设置单个⼯作进程的最⼤并发连接数
    use epoll; # 使⽤epoll事件驱动,Nginx⽀持众多的事件驱动,⽐如select、poll、epoll,只能设置在events模块中设置。
    accept_mutex on; # 优化同⼀时刻只有⼀个请求⽽避免多个睡眠进程被唤醒的设置,on为防⽌被同时唤醒默
                     # 认为off,全部唤醒的过程也成为"惊群",因此nginx刚安装完以后要进⾏适当的优化。
    multi_accept on; # Nginx服务器的每个⼯作进程可以同时接受多个新的⽹络连接,但是需要在配置⽂件中
                     # 配置,此指令默认为关闭,即默认为⼀个⼯作进程只能⼀次接受⼀个新的⽹络连接,打开后⼏个同时接受多个。
}

http详细配置

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  logs/access.log  main;

    # ⾃定义优化参数
    sendfile        on; # 实现⽂件零拷⻉
    #tcp_nopush     on; # 在开启了sendfile的情况下,合并请求后统⼀发送给客⼾端。
    #tcp_nodelay    off; # 在开启了keepalived模式下的连接是否启⽤TCP_NODELAY选项,当为off时,延
                         # 迟0.2s发送,默认On时,不延迟发送,⽴即发送⽤⼾相应报⽂。
    #keepalive_timeout  0;
    keepalive_timeout  65 65; # 设置会话保持时间
    #gzip  on; # 开启⽂件压缩

server {
        listen       80; # 设置监听地址和端⼝
        server_name  localhost; # 设置server name,可以以空格隔开写多个并⽀持正则表达式,如
                                # *.magedu.com www.magedu.* www.(site\d+)\.magedu\.com$ default_server
        #charset koi8-r; # 设置编码格式,默认是俄语格式,可以改为utf-8
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html; # 定义错误⻚⾯
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ { #以http的⽅式转发php请求到指定web服务器
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ { #以fastcgi的⽅式转发php请求到php处理
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht { #拒绝web形式访问指定⽂件,如很多的⽹站都是通过.htaccess⽂件来改变⾃⼰的重定向等功能。
        #    deny  all;
        #}
        location ~ /passwd.html {
            deny  all;
        }
        }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server { #⾃定义虚拟server
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm; #指定默认⽹⻚⽂件,此指令由ngx_http_index_module模块提供

    #    }
    #}

    # HTTPS server
    #
    #server { #https服务器配置
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    location  /linux38/passwd.ht {
      deny  all;
     }

    #}

核心配置示例

  • 基于不同的IP、不同的端⼝以及不⽤得域名实现不同的虚拟主机,依赖于核⼼模块ngx_http_core_module实现。
//修改主配置文件设置,子配置文件路径
vim /apps/nginx/conf/nginx.conf

//http块中添加,子配置文件路径
include /apps/nginx/conf/conf.d/*.conf;
--------------------------
//新建编辑pc端子配置文件
vim /apps/nginx/conf/conf.d/pc.conf

//配置文件内容
server{
listen 80;
server_name www.pc.com;
location / {
	root /data/nginx/html/pc;
}
}
---------------------------
//新建编辑mobile端子配置文件
vim /apps/nginx/conf/conf.d/mobile.conf

//配置文件内容
server{
listen 80;
server_name www.mobile.com;
location / {
    root /data/nginx/html/mobile;                                              
}
}
-----------------------------
//创建测试页面
echo "this is pc web" > /data/nginx/html/pc/index.html

echo "this is mobile web" > /data/nginx/html/mobile/index.html

//重新加载配置文件
/apps/nginx/sbin/nginx -s reload 

//修改windows中hosts文件内容添加
172.20.26.104   www.pc.com
172.20.26.104   www.mobile.com
  • 浏览器访问http://www.pc.com/得

在这里插入图片描述

  • 浏览器访问http://www.mobile.com/得

在这里插入图片描述

  • root与alias
  • root:指定web的家⽬录,在定义location的时候,⽂件的绝对路径等于 root+location,如:
//编辑pc端子配置文件
vim /apps/nginx/conf/conf.d/pc.conf

//配置文件如下
server{
listen 80;
server_name www.pc.com;
location / {
	root /data/nginx/html/pc;
}
location /images{
	root /data/nginx/html/pc   #必须要在/pc目录中创建/images目录存放图片才可访问
	index index.html
}
}
----------------------------------------
//查看图片存放位置
tree /data/nginx/html/pc/images/

/data/nginx/html/pc/images/
└── ms.jpg

  • 浏览器访问http://www.pc.com/images/ms.jpg得

在这里插入图片描述

  • alias:定义路径别名,会把访问的路径重新定义到其指定的路径,如:
//编辑pc端子配置文件
vim /apps/nginx/conf/conf.d/pc.conf

server{
listen 80;
server_name www.pc.com;
location / {
	root /data/nginx/html/pc;
}
location /images{ #使⽤alias的时候uri后⾯如果加了斜杠则下⾯的路径配置必须加斜杠,否则403
	alias /data/nginx/html/pc   #当访问images的时候,会显⽰alias定义的/data/nginx/html/pc⾥⾯的
内容。
	index index.html
}
}
-------------------------------------------
//查看图片存放位置
tree /data/nginx/html/pc/

/data/nginx/html/pc/
├── images
├── index.html
└── ms.jpg
  • 浏览器访问http://www.pc.com/images/ms.jpg得

在这里插入图片描述

Nginx四层访问控制

location /about {
alias /data/nginx/html/pc;
index index.html;
deny 192.168.1.1;   #拒绝地址
allow 192.168.1.0/24;   #允许网段
allow 10.1.1.0/16;   #允许网段
allow 2001:0db8::/32;   #允许IPV6地址
deny all; #先允许⼩部分,再拒绝⼤部分
}

Nginx账户认证功能

//安装httpd工具包
yum -y install httpd-tools   #centos

apt -y isntall apache2-utils   #ubuntu

//设置用户1以及密码
htpasswd -cbm /apps/nginx/conf/.htpasswd bokebi1 123456
Adding password for user bokebi1

//设置用户2以及密码
htpasswd -bm /apps/nginx/conf/.htpasswd bokebi2 123456
Adding password for user bokebi2

//查看密码文件
tail /apps/nginx/conf/.htpasswd
user1:$apr1$Rjm0u2Kr$VHvkAIc5OYg.3ZoaGwaGq/
user2:$apr1$nIqnxoJB$LR9W1DTJT.viDJhXa6wHv.

//编辑pc端子配置文件
vim /apps/nginx/conf/conf.d/pc.conf
location = /login/ {
root /data/nginx/html/pc;
index index.html;
auth_basic "login password";   #加入这行
auth_basic_user_file /apps/nginx/conf/.htpasswd;   #指定用户密码存放路径
}
重启nginx并访问测试

自定义错误页面

listen 80;
server_name www.magedu.net;
error_page 500 502 503 504 404 /error.html;
location = /error.html {
root html;
}
重启nginx并访问不存在的⻚⾯进⾏测试

自定义访问日志

[root@s2 ~]# mkdir /data/nginx/logs
listen 80;
server_name www.magedu.net;
error_page 500 502 503 504 404 /error.html; #默认⽬录下⾯创建error.html⻚⾯
access_log /data/nginx/logs/www-magedu-net_access.log;   #nginx用户要对创建的目录有操作权限
error_log /data/nginx/logs/www-magedu-net_error.log;   #nginx用户要对创建的目录有操作权限
location = /error.html {
root html;
}
重启nginx并访问不存在的⻚⾯进⾏测试并验证是在指定⽬录⽣成新的⽇志⽂件

检测文件是否存在

  • try_files会按顺序检查⽂件是否存在,返回第⼀个找到的⽂件或⽂件夹(结尾加斜线表⽰为⽂件夹),如果所有⽂件或⽂件夹都找不到,会进⾏⼀个内部重定向到最后⼀个参数。只有最后⼀个参数可以引起⼀个内部重定向,之前的参数只设置内部URI的指向。最后⼀个参数是回退URI且必须存在,否则会出现内部500错误。
location /about {
root /data/nginx/html/pc;
#alias /data/nginx/html/pc;
index index.html;
#try_files $uri /about/default.html;
#try_files $uri $uri/index.html $uri.html /about/default.html;
try_files $uri $uri/index.html $uri.html =489;
}
[root@s2 ~]# echo "default" >> /data/nginx/html/pc/about/default.html
重启nginx并测试,当访问到http://www.pc.com/about/xx.html等不存在的uri会显⽰default,如果
是⾃定义的状态码则会显⽰在返回数据的状态码中,如:
[root@s2 about]# curl --head http://www.pc.com/about/xx.html
HTTP/1.1 489 #489就是⾃定义的状态返回码
Server: nginx
Date: Thu, 21 Feb 2019 00:11:40 GMT
Content-Length: 0
Connection: keep-alive
Keep-Alive: timeout=65

长连接配置

  • keepalive_timeout number; #设定保持连接超时时⻓,0表⽰禁⽌⻓连接,默认为75s,通常配置在http字段作为站点全局配置 keepalive_requests number; #在⼀次⻓连接上所允许请求的资源的最⼤数量,默认为100次
keepalive_requests 3;
keepalive_timeout 65 65;
开启⻓连接后,返回客⼾端的会话保持时间为60s,单次⻓连接累计请求达到指定次数请求或65秒就会被断开,后⾯的
60为发送给客⼾端应答报⽂头部中显⽰的超时时间设置为60s:如不设置客⼾端将不显⽰超时时间。
Keep-Alive:timeout=60 #浏览器收到的服务器返回的报⽂
如果设置为0表⽰关闭会话保持功能,将如下显⽰:
Connection:close #浏览器收到的服务器返回的报⽂
//使⽤命令测试:
telnet www.magedu.net 80

  Trying 172.18.200.102...
Connected to www.pc.com
Escape character is '^]'.
GET / HTTP/1.1
HOST: www.pc.com

#Response Headers(响应头信息):
HTTP/1.1 200 OK
Server: nginx/1.14.2
Date: Thu, 14 Mar 2019 17:23:46 GMT
Content-Type: text/html
Content-Length: 7
Last-Modified: Thu, 14 Mar 2019 14:54:50 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "5c8a6b3a-7"
Accept-Ranges: bytes

#⻚⾯内容
pc web

作为下载服务器配置

//创建所需目录
mkdir /data/nginx/html/pc/download   #download不需要index.html⽂件

//编辑配置文件
vim /apps/nginx/conf/conf.d/pc.conf

location /download {
autoindex on; #⾃动索引功能
autoindex_exact_size on; #计算⽂件确切⼤⼩(单位bytes),off只显⽰⼤概⼤⼩(单位kb、mb、
gb)
autoindex_localtime on; #显⽰本机时间⽽⾮GMT(格林威治)时间
root /data/nginx/html/pc;
}

limit_rate rate; #限制响应给客⼾端的传输速率,单位是bytes/second,默认值0表⽰⽆限制
限速与不限速的对⽐:
limit_rate 10k;

#可以使用wget下载资源进行测试下载速度
  • 浏览器访问http://www.pc.com/download/得

在这里插入图片描述

作为上传服务器配置

client_max_body_size 1m; #设置允许客⼾端上传单个⽂件的最⼤值,默认值为1m
client_body_buffer_size size; #⽤于接收每个客⼾端请求报⽂的body部分的缓冲区⼤⼩;默认16k;超出
此⼤⼩时,其将被暂存到磁盘上的由下⾯client_body_temp_path指令所定义的位置
client_body_temp_path path [level1 [level2 [level3]]];
#设定存储客⼾端请求报⽂的body部分的临时存储路径及⼦⽬录结构和数量,⽬录名为16进制的数字,使⽤hash之后的
值从后往前截取1位、2位、2位作为⽂件名:
[root@s3 ~]# md5sum /data/nginx/html/pc/index.html
95f6f65f498c74938064851b1bb 96 3d 4 /data/nginx/html/pc/index.html
1级⽬录占1位16进制,即2^4=16个⽬录 0-f
2级⽬录占2位16进制,即2^8=256个⽬录 00-ff
3级⽬录占2位16进制,即2^8=256个⽬录 00-ff
配置⽰例(一般作为默认配置,所以放置在主配置文件里):
client_max_body_size 10m;
client_body_buffer_size 16k;
client_body_temp_path /apps/nginx/temp 1 2 2; #reload Nginx会⾃动创建temp⽬录

其他配置

limit_except

  • 限制客户端使用除了指定的请求方法之外的其它方法,只能用在location上下文。

在这里插入图片描述

  • method:
GET, HEAD, POST, PUT, DELETE

MKCOL, COPY, MOVE, OPTIONS, PROPFIND,

PROPPATCH, LOCK, UNLOCK, PATCH
  • 示例:
limit_except GET HEAD POST {
    deny 192.168.111.200
    allow 192.168.111.0/24;
    deny all;
}
  • 表示除了GET、HEAD、POST方法其他方法都限制,
  • 主机范围为:禁止192.168.111.200、允许192.168.111.0/24、禁止所有。
  • 即仅允许192.168.111.0网段访问,但是禁止192.168.111.200的地址访问

aio

  • 是否启用异步I/O功能

在这里插入图片描述

  • linux 2.6以上内核提供以下⼏个系统调⽤来⽀持aio:
    • 1、SYS_io_setup:建⽴aio 的context
    • 2、SYS_io_submit: 提交I/O操作请求
    • 3、SYS_io_getevents:获取已完成的I/O事件
    • 4、SYS_io_cancel:取消I/O操作请求
    • 5、SYS_io_destroy:毁销aio的context

directio

  • 是否同步写磁盘
    在这里插入图片描述
  • 操作完全和aio相反,aio是读取⽂件⽽directio是写⽂件到磁盘
  • 启⽤直接I/O,默认为关闭,当⽂件⼤于等于给定⼤⼩时,例如directio 4m,同步(直接)写磁盘,⽽⾮写缓存。

open_file_cache

  • 是否缓存打开过的⽂件信息
    在这里插入图片描述
  • nginx可以缓存以下三种信息:
    (1) ⽂件元数据:⽂件的描述符、⽂件⼤⼩和最近⼀次的修改时间
    (2) 打开的⽬录结构
    (3) 没有找到的或者没有权限访问的⽂件的相关信息
  • max=N:可缓存的缓存项上限数量;达到上限后会使⽤LRU(Least recently used,最近最少使⽤)算法实现
    管理
  • inactive=time:缓存项的⾮活动时⻓,在此处指定的时⻓内未被命中的或命中的次数少于
    open_file_cache_min_uses指令所指定的次数的缓存项即为⾮活动项,将被删除

open_file_cache_errors

  • 是否缓存查找时发⽣错误的⽂件⼀类的信息(默认值为off)
    在这里插入图片描述

open_file_cache_min_uses

  • open_file_cache指令的inactive参数指定的时⻓内,⾄少被命中此处指定的次数⽅可被归类为活动项(默认值为1)
    在这里插入图片描述

open_file_cache_valid

  • 缓存项有效性的检查验证频率(默认值为60s)
    在这里插入图片描述
  • 示例
aio                      on;                         # 开启异步I/O
directio                 4m;                         # 开启同步磁盘文件大小>4M
open_file_cache          max=1000 inactive=20s;      # 最⼤缓存1000个⽂件,⾮活动数据超时时⻓20s
open_file_cache_valid    30s;                        # 每间隔30s检查⼀下缓存数据有效性
open_file_cache_min_uses 2;                          # 30秒内⾄少被命中访问2次才被标记为活动数据
open_file_cache_errors   on;                         # 缓存错误信息
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值