Nginx之常用基本配置(一)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Nginx之常用基本配置(一)

Linux-1874   2020-02-28 我要评论

  上一篇博客我们大概介绍了一下nginx,nginx的架构,nginx编译安装和nginx命令的用法,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/12366808.html;今天我们来配置简单的配置下nginx和一些简单指令说明。

  nginx和httpd类似都是高度模块化的软件,不同的模块有着不同的功能,想要把nginx配置好,首先我们需要了解各个模块的用法以及模块选项的用法和说明。首先我们来了解下nginx用yum安装后,程序环境

[root@www ~]# rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx/fastcgi.conf
/etc/nginx/fastcgi.conf.default
/etc/nginx/fastcgi_params
/etc/nginx/fastcgi_params.default
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/mime.types.default
/etc/nginx/nginx.conf
/etc/nginx/nginx.conf.default
/etc/nginx/scgi_params
/etc/nginx/scgi_params.default
/etc/nginx/uwsgi_params
/etc/nginx/uwsgi_params.default
/etc/nginx/win-utf
/usr/bin/nginx-upgrade
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx/modules
/usr/sbin/nginx
/usr/sharehttps://img.qb5200.com/download-x/doc/nginx-1.16.1
……省略部分内容
/var/lib/nginx
/var/lib/nginx/tmp
/var/log/nginx
[root@www ~]# 

  提示:从上面的显示,我们大概可以了解到nginx的主配置文件是/etc/ngxin/ngxin.conf,nginx.conf.default是默认配置文件,从这个文件中我们可以了解到nginx的默认配置是怎么配置的;主程序是/usr/sbin/nginx,日志文件路径是/var/log/nginx,Unit File是nginx.service;/etc/nginx/fastcgi.conf和fastcgi_parems,这两个文件一个是fastcig协议的配置文件,一个是变量配置文件。了解了nginx 的程序环境,我们在来看看主配置文件内容

[root@www ~]# cat /etc/nginx/nginx.conf
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/enhttps://img.qb5200.com/download-x/docs/
#   * Official Russian Documentation: http://nginx.org/ruhttps://img.qb5200.com/download-x/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/sharehttps://img.qb5200.com/download-x/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/enhttps://img.qb5200.com/download-x/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginxhttps://img.qb5200.com/download-x/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginxhttps://img.qb5200.com/download-x/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

[root@www ~]# 

  提示:主配置文件结构大致可以分为main段(全局配置段)和http配置段或者mail配置段或者stream段,后面的http配置段或mail配置段或stream配置段,主要看nginx用于什么功能,如果单纯的用于web服务器,那么后面的mail和stream配置段就可以不要了,也就是说有关web的配置我们必须要在http配置段配置;同样的如果nginx用于邮件代理我们就需要把有关邮件代理的配置放到mail配置段,如果用于四层负载均衡,我们需要把对应的配置写到stream配置段;我们先说一下全局配置段吧

  user指令:表示指定运行worker进程的用户

[root@www ~]# head /etc/nginx/nginx.conf
  For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/enhttps://img.qb5200.com/download-x/docs/
#   * Official Russian Documentation: http://nginx.org/ruhttps://img.qb5200.com/download-x/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/sharehttps://img.qb5200.com/download-x/doc/nginx/README.dynamic.
[root@www ~]# ps aux |grep nginx
root       1425  0.0  0.0 120832  2244 ?        Ss   19:49   0:00 nginx: master process nginx
nginx      1426  0.0  0.0 121228  3132 ?        S    19:49   0:00 nginx: worker process
nginx      1427  0.0  0.0 121228  3132 ?        S    19:49   0:00 nginx: worker process
nginx      1428  0.0  0.0 121228  3132 ?        S    19:49   0:00 nginx: worker process
nginx      1429  0.0  0.0 121228  3132 ?        S    19:49   0:00 nginx: worker process
root       1439  0.0  0.0 112660   968 pts/0    S+   19:51   0:00 grep --color=auto nginx
[root@www ~]#

  提示:通常情况都不建议nginx用root运行;如果是集群环境建议统一进程运行用户,其次必须统一时间

  worker_processes :指定worker进程的数量,一般是和运行nginx主机的CUP核心数来定,一般都是小于或者等于物理cpu核心数,auto表示自动去匹配cup核心数来启动worker进程数量

[root@www ~]# lscpu 
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             2
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 158
Model name:            Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz
Stepping:              9
CPU MHz:               3599.644
CPU max MHz:           0.0000
CPU min MHz:           0.0000
BogoMIPS:              7200.06
Hypervisor vendor:     VMware
Virtualization type:   full
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              8192K
NUMA node0 CPU(s):     0-3
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid rtm rdseed adx smap xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp
[root@www ~]# ps aux |grep nginx
root       1425  0.0  0.1 121500  5272 ?        Ss   19:49   0:00 nginx: master process nginx
nginx      1453  0.0  0.0 121748  3668 ?        S    19:56   0:00 nginx: worker process
nginx      1454  0.0  0.0 121748  3668 ?        S    19:56   0:00 nginx: worker process
nginx      1455  0.0  0.0 121748  3668 ?        S    19:56   0:00 nginx: worker process
nginx      1456  0.0  0.0 121748  3668 ?        S    19:56   0:00 nginx: worker process
root       1465  0.0  0.0 112660   972 pts/0    S+   19:57   0:00 grep --color=auto nginx
[root@www ~]# 

  error_log表示指定nginx错误日志存放文件

[root@www ~]# ll /var/log/nginx/error.log 
-rw-r--r-- 1 root root 120 Feb 27 19:56 /var/log/nginx/error.log
[root@www ~]# cat /var/log/nginx/error.log
2020/02/27 19:52:18 [notice] 1442#0: signal process started
2020/02/27 19:56:47 [notice] 1452#0: signal process started
[root@www ~]# 

  pid表示指定pid文件

[root@www ~]# ps aux |grep nginx
root       1567  0.0  0.0 120832  2248 ?        Ss   20:05   0:00 nginx: master process /usr/sbin/nginx
nginx      1568  0.0  0.0 121228  3336 ?        S    20:05   0:00 nginx: worker process
nginx      1569  0.0  0.0 121228  3336 ?        S    20:05   0:00 nginx: worker process
nginx      1570  0.0  0.0 121228  3336 ?        S    20:05   0:00 nginx: worker process
nginx      1571  0.0  0.0 121228  3136 ?        S    20:05   0:00 nginx: worker process
root       1574  0.0  0.0 112660   972 pts/0    S+   20:05   0:00 grep --color=auto nginx
[root@www ~]# ll /var/run/nginx.pid 
-rw-r--r-- 1 root root 5 Feb 27 20:05 /var/run/nginx.pid
[root@www ~]# nginx -s stop
[root@www ~]# ll /var/run/nginx.pid 
ls: cannot access /var/run/nginx.pid: No such file or directory
[root@www ~]# 

  提示:pid文件就是存放nginx主控进程的进程号的,如果nginx没有运行或者停止了服务,那么pid文件也会跟着消失;这里提示一下在centos7上/var/run 和/run是同一文件夹 ,它俩做的是硬链接

[root@www ~]# ll -id /var/run/
1150 drwxr-xr-x 22 root root 620 Feb 27 20:07 /var/run/
[root@www ~]# ll -id /run
1150 drwxr-xr-x 22 root root 620 Feb 27 20:07 /run
[root@www ~]# 

  提示:两个文件夹的inode号都是同一个

  include此指令表示把某些地方的配置导入到此地;这个指定配置的时候需要注意放的位置;正因为有了这个功能,我们就可以把很多不同功能的配置用专有的文件来配置,这样既方便管理,也很容易读;

  events此配置段表示配置有关事件驱动相关的配置

  worker_connections :每个worker进程所能够打开的最大并发连接数;

  use method:指定并发请求的处理方法;如use epoll;

  accept_mutex on|off:处理新的连接请求的方法;on表示各worker进程轮流处理新请求,off表示每来一个新请求就会通知所有的worker进程

  有关性能优化的全局配置

  worker_cpu_affinity cpumask:手动或自动绑定cpu,默认情况下是没有绑定cpu的,这意味着worker进程会在每个CPU上来会调度的,这样一来在cpu就存在频繁的切换,影响性能;我们可以手动把每个进程绑定到不同的CPU上。禁止worker进程在每个CPU上来回切换

 

  提示:在没有绑定cpu时,我们对nginx worker进程发起并发连接请求,可以看到4个worker进程在不同的CUP上来回切换,很显然这无疑在给系统多余的开销,我们可以绑定nginx 的worker线程。

[root@www ~]# grep worker_cpu /etc/nginx/nginx.conf
worker_cpu_affinity 0001 0010 0100 1000;
[root@www ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www ~]# nginx -s reload
[root@www ~]# 

  提示:如果你有的CPU是八核的,那么就需要用8个0来表示,其中第一个进程对应最右侧的0,如果需要绑定到该cpu核心上,则对应位为1即可;

  提示:绑定cpu我们也可以直接使用worker_cpu_affinity auto;来指定,让其自动绑定到每个cpu核心上去

   worker_priority number:指定worker进程的nice值,设定worker进程优先级;[-20,19]

[root@www ~]# grep "worker_priority" /etc/nginx/nginx.conf
worker_priority -5;
[root@www ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www ~]# nginx -s reload                             
[root@www ~]# ps axo comm,pid,nice,psr|grep nginx
nginx             2583   0   0
nginx            31567  -5   0
nginx            31568  -5   1
nginx            31569  -5   2
nginx            31570  -5   3
[root@www ~]# 

  以上就是常用的全局配置段指令的说明和使用,详细请参考nginx官方文档http://nginx.org/enhttps://img.qb5200.com/download-x/docs/ngx_core_module.html

  http协议的相关配置

  在主配置文件中我们可以看到有一个以http开头的配置段,这个配置段主要配置nginx工作成web服务的配置

  server:这个指令表示定义个虚拟主机类似httpd里的virtualhost,这也是一个http里的一个子配置段,里面有server_name指令 root等等

    server_name:表示指定虚拟主机名称;指明虚拟主机的主机名称;后可跟多个由空白字符分隔的字符串;支持*通配任意长度的任意字符;支持~起始的字符做正则表达式模式匹配;

      匹配机制:首先是字符串精确匹配;其次是左侧*通配符,然后右侧*通配符,最后是正则表达式

    root:设置web资源路径映射;用于指明用户请求的url所对应的本地文件系统上的文档所在目录路径;可用的位置:http, server, location, if in location;

    listen:指定虚拟主机监听的地址和端口,如果只指定端口未指定地址,表示监听服务器上的所有地址,如果在server里没有指定端口,对应的虚拟主机将监听在默认端口80上

      listen address[:port] [default_server] [ssl] [http2 | spdy]  [backlog=number] [rcvbuf=size] [sndbuf=size]

        default_server:设定为默认虚拟主机;

        ssl:限制仅能通过ssl连接该服务

        backlog=number:指定后援队列长度

        sndbuf=size:指定发送缓冲区大小

 

   提示:我们这样配置后,在hosts文件中添加对应的解析后,用浏览器访问www.ilinux.io,此时它就会把默认主机里的映射路径下的资源响应我们

[root@www ~]# echo "this is default path " > /usr/share/nginx/html/test.html
[root@www ~]# cat /usr/share/nginx/html/test.html
this is default path 
[root@www ~]# curl http://www.ilinux.io/test.html
this is default path 
[root@www ~]# 

    tcp_nodelay on|off :在keepalived模式下的连接是否启用TCP_NODELAY选项;

    tcp_nopush on|off:在sendfile模式下,是否启用TCP_CORK选项;

    sendfile on|off:是否启用sendfile功能;

  通常情况下以上三项都是打开的,TCP_NODELAY主要是发送报文延时问题,如果开启了该功能选项,表示不管数据包多小都及时发送,如果关闭了,通常会等到一定量的数据报文一起发送,对于小报文延时就很高,TCP_CORK主要是解决小包问题,它和TCP_NODELAY相反,启用表示要到一定量的数据包后才发送,关闭表示不用等一定量的数据报文再发送,它们两者都是解决小包问题,前者应用在长连接模式下,后者应用在sendfile模式下;sendfile模式解决了内核到用户应用程序,用户应用程序到内核的重复过程,它可将数据报文直接从内核加载到网卡socket缓存区,直接发送出去;这三项都和性能相关,通常都是开启的;

  location:此指令用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配,而后应用其配置;在一个server中location配置段可存在多个;

    语法:location [ = | ~ | ~* | ^~ ] uri { ... }

      =:对URI做精确匹配;

      ^~:对URI的左半部分做匹配检查,不区分字符大小写;

      ~:对URI做正则表达式模式匹配,区分字符大小写;

      ~*:对URI做正则表达式模式匹配,不区分字符大小写;

      不带符号:匹配起始于此uri的所有的url;

      匹配优先级:=, ^~, ~/~*,不带符号;

   示例:

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location https://img.qb5200.com/download-x/documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

  说明:如果是用户请求uri是/ 那么在以上location中将匹配到A,如果是/index 将匹配到B,如果是https://img.qb5200.com/download-x/documents/index将匹配到C,如果是/images/1.jpg将匹配到D和E,但是D的优先级高于E,所有应用D的配置,如果是https://img.qb5200.com/download-x/document/1.jpg将匹配到C和E,但是E的优先级高于C,所以会应用E的配置;

  alias path:定义资源路径别名,仅用于location中;它和root定义资源路径不同的是,root定义的资源路径应用在/uri/左侧的'/',而alias定义的资源路径应用在/uri/的右侧'/';

  示例:

[root@www ~]# cat /etc/nginx/conf.d/test.conf
server {

        listen 80;
        server_name www.ilinux.io;

        location  /test/ {
                root https://img.qb5200.com/download-x/data/web/html/;

                allow all;
        }
}
[root@www ~]# cat https://img.qb5200.com/download-x/data/web/html/index.html 
this is https://img.qb5200.com/download-x/data/web/html/index.html
[root@www ~]# cat https://img.qb5200.com/download-x/data/web/html/index.html 
this is https://img.qb5200.com/download-x/data/web/html/index.html
[root@www ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www ~]# nginx -s reload
[root@www ~]# curl http://www.ilinux.io/test/index.html
this is https://img.qb5200.com/download-x/data/web/html/test/index.html
[root@www ~]# 

  提示:我们用root来指定资源路径时,我们访问/test/.index.html 它返回的是https://img.qb5200.com/download-x/data/web/html/test/index.html,就相当于把location左侧的“/”更换成root定义的路径,用户访问资源的真实路径就是https://img.qb5200.com/download-x/data/web/html/test/index.html;换句话讲,root指定资源路径,匹配用户URI最左侧“/”,真实路径是root指定的路径+用户URI(不带左侧"/")

[root@www ~]# cat /etc/nginx/conf.d/test.conf 
server {

        listen 80;
        server_name www.ilinux.io;

        location  /test/ {
                alias https://img.qb5200.com/download-x/data/web/html/;

                allow all;
        }
}
[root@www ~]# cat https://img.qb5200.com/download-x/data/web/html/index.html 
this is https://img.qb5200.com/download-x/data/web/html/index.html
[root@www ~]# cat https://img.qb5200.com/download-x/data/web/html/test/index.html 
this is https://img.qb5200.com/download-x/data/web/html/test/index.html
[root@www ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www ~]# nginx -s reload
[root@www ~]# curl http://www.ilinux.io/test/index.html
this is https://img.qb5200.com/download-x/data/web/html/index.html
[root@www ~]# 

  提示:用alias 指定资源路径时,我们访问/test/index.html,它返回https://img.qb5200.com/download-x/data/web/html/index.html,相当于alias 指定的资源路径覆盖了用户请求的URI最右侧的“/”,换句话说用户URI最右侧的“/”就是alias所指定的资源路径,用户访问/test/index.html 就相当于访问https://img.qb5200.com/download-x/data/web/html/index.html;这里还需要注意一点的是 alias 指定资源路径时,必须是“/”结尾,如果不以“/”结尾,资源将无法找到;对于root来讲是不是“/”结尾这个无要求;

  index file:指定默认主页,可配置在http, server, location;

  示例:

[root@www html]# cat /etc/nginx/conf.d/test.conf 
server {

        listen 80;
        server_name www.ilinux.io;
        location  /test/ {
                alias https://img.qb5200.com/download-x/data/web/html/;
                index test.html;
                allow all;
        }
}
[root@www html]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www html]# nginx -s reload
[root@www html]# curl http://www.ilinux.io/test/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>
[root@www html]# echo "this is default page" > https://img.qb5200.com/download-x/data/web/html/test.html
[root@www html]# curl http://www.ilinux.io/test/                       
this is default page
[root@www html]# 

  error_page code ... [=[response]] uri:指定错误页面,匹配指定的状态码,返回指定的URL

  示例:

[root@www html]# cat /etc/nginx/conf.d/test.conf
server {

        listen 80;
        server_name www.ilinux.io;
        location  /test/ {
                alias https://img.qb5200.com/download-x/data/web/html/;
                index test.html;
                allow all;
        }
        error_page 404 403 /error.html;

        location /error.html {
                root https://img.qb5200.com/download-x/data/web/html/error;
        }
}
[root@www html]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@www html]# nginx -s reload
[root@www html]# mkdir https://img.qb5200.com/download-x/data/web/html/error/
[root@www html]# echo "error page" > https://img.qb5200.com/download-x/data/web/html/error/error.html
[root@www html]# curl http://www.ilinux.io/abc/
error page
[root@www html]# 

  提示:通过指定错误页面,我们可以自定义错误页面,也可以对错误页面用专有的location来做配置;

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们