nginx配置文件详解

Nginx的主配置文件由指令与指令块构成,指令块以{ }大括号将多条指令组织在一起

· 每条指令以;分号结尾,指令与参数间用空格分隔

· 支持include语句组合多个配置文件,提升可维护性

· #表示注释,$表示变量,部分指令的参数支持正则表达式

3、编译安装Nginx,常用选项: 

--prefix=path:设置Nginx的安装路径,不写的话默认是在/usr/local/nginx
--sbin-path=path:设置Nginx的可执行文件路径,默认路径是prefix/sbin/nginx
--conf-path=path:设置Nginx配置文件路径,默认路径是prefix/conf/nginx.conf
--pid-path=path:设置Nginx pid文件路径,默认路径是prefix/logs/nginx.pid
--error-log-path=path:设置错误日志存放路径,默认路径是prefix/logs/error.log
--http-log-path=path:设置访问日志存放路径,默认路径是prefix/logs/access.log
--user=name:设置运行Nginx的用户,默认用户是nobody
--group=name:设置运行Nginx的用户组,默认用户组是nobody
  --with-http_ssl_module             enable ngx_http_ssl_module
  --with-http_v2_module              enable ngx_http_v2_module
  --with-http_realip_module          enable ngx_http_realip_module
  --with-http_addition_module        enable ngx_http_addition_module
  --with-http_xslt_module            enable ngx_http_xslt_module
  --with-http_xslt_module=dynamic    enable dynamic ngx_http_xslt_module
  --with-http_image_filter_module    enable ngx_http_image_filter_module
  --with-http_image_filter_module=dynamic
                                     enable dynamic ngx_http_image_filter_module
  --with-http_geoip_module           enable ngx_http_geoip_module
  --with-http_geoip_module=dynamic   enable dynamic ngx_http_geoip_module
  --with-http_sub_module             enable ngx_http_sub_module
  --with-http_dav_module             enable ngx_http_dav_module
  --with-http_flv_module             enable ngx_http_flv_module
  --with-http_mp4_module             enable ngx_http_mp4_module
  --with-http_gunzip_module          enable ngx_http_gunzip_module
  --with-http_gzip_static_module     enable ngx_http_gzip_static_module
  --with-http_auth_request_module    enable ngx_http_auth_request_module
  --with-http_random_index_module    enable ngx_http_random_index_module
  --with-http_secure_link_module     enable ngx_http_secure_link_module
  --with-http_degradation_module     enable ngx_http_degradation_module
  --with-http_slice_module           enable ngx_http_slice_module
  --with-http_stub_status_module     enable ngx_http_stub_status_module

5、Nginx主配置文件(/usr/local/nginx/conf/nginx.conf)详解:

events
│
http
├── server1
│   ├── location1 标签是做匹配    
│   ├── location2
│   
├── server2

每个主机都配置在server标签里

Location标签的匹配规则:

=  #精确匹配,优先级最高
^~  #普通字符串匹配,禁止正则表达式,当匹配成功后停止其他location匹配,优先级高于正则
~  #区分大小写的正则匹配
~*  #不区分大小写的正则匹配

未做任何配置的配置文件:

#user  nobody;    #默认运行Nginx的用户名
worker_processes  1;    #开启的进程数,通常和cpu个数相等
events {
    worker_connections  1024;    #每个进程的并发数
}
http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;      #长连接超时时间为65秒

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }

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

    }
user nginx;  #运行Nginx的用户
worker_processes  2;    #开启的进程数,通常和cpu个数相等或者设置为auto
worker_cpu_affinity auto;  #自动进行CPU亲和设置
#worker_cpu_affinity 0000000000000001 000000000000010 #手动进行CPU亲和设置
error_log  logs/error.log warn;  #Nginx服务的错误日志路径与记录级别
pid  /var/run/nginx.pid;
worker_rlimit_nofile 65535;  #设置Nginx进程文件句柄数
events {
    worker_connections  10240;    #每个进程的并发数
}

http {
  include       mime.types;
  default_type  application/octet-stream;
  charset utf-8;
  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;  #访问日志存放路径与日志记录格式,这里main就是上一步log_format所定义的main
  sendfile        on;
  tcp_nopush     on;  #一次传输多个数据包,提高传输效率
  #tcp_nodeley    off  #与tcp_nopush相反,实时性要求比较高的场景会打开这个
  keepalive_timeout  65;    #长连接超时时间为65秒
  gzip  on;  #打开gzip后通过浏览器开发者工具-网络功能可以看到size大小被压缩了,对文本类型的文件压缩效率最高,可作用于location中
  include /etc/nginx/conf.d/*.conf  #conf.d目录下的配置文件也会生效
  server {
      listen       80;
      server_name  localhost;
      #charset koi8-r;
      access_log  logs/access.log  main;  #单独对主机记录日志
      location ~ .*.(jpg|gif|png)$ {
          gzip  on;
          expires 24h;  #开启缓存,如果是取的缓存数据,浏览器开发者工具中返回状态是304
          root   html;
          index  index.html index.htm;
      }
      #error_page  404              /404.html;
      error_page   500 502 503 504  /50x.html;
      location = /50x.html {
          root   html;
        }

1.rewrite的介绍

nginx的rewrite规则就是使用正则匹配请求的url,然后根据定义的规则进行重写和改变,需ngx_http_rewrite_module模块来支持url重写功能,该模块是标准模块,默认已经安装。

url和uri的区别:

URI:Universal Resource Identifier ,通用资源标识符,用于对网络中的各种资源进行标识,由存放资源的主机名、片段标志符和相对的URI三部分组成。存放资源的主机名一般由传输协议(Scheme)、主机和资源路径三部分组成;片段标识符指向资源内容的具体元素、相对URI表示资源在主机上的相对路径。一般格式为:Scheme://[用户名][:密码]@主机名[:端口号][/资源路径]

URL:Uniform Resource Location,统一资源定位符,是用于在Internet中描述资源的字符串,是URI的子集,主要包括传输协议(Scheme)、主机(IP、端口号或者域名)和资源集体地址(目录或文件名)等三部分,一般格式为:scheme://主机名[:端口号]/[资源路径]

2.rewrite涉及的指令

执行顺序:

1.执行server块的rewrite指令(这里的块指的是server关键字后{}包围的区域,其它xx块类似)
2.执行location匹配
3.执行选定的location中的rewrite指令
如果其中某步URI被重写,则重新循环执行1-3,直到找到真实存在的文件

如果循环超过10次,则返回500 Internal Server Error错误

1)if指令

    语法:if(condition){...}

默认值:无

作用域:server,location

对给定的条件condition进行判断。如果为真,大括号内的rewrite指令将被执行。

if条件(conditon)可以是如下任何内容:

 

一个变量名;false如果这个变量是空字符串或者以0开始的字符串;

使用= ,!= 比较的一个变量和字符串,true/false

使用~, ~*与正则表达式匹配的变量,如果这个正则表达式中包含右花括号}或者分号;则必须给整个正则表达式加引号

使用-f ,!-f 检查一个文件是否存在

使用-d, !-d 检查一个目录是否存在

使用-e ,!-e 检查一个文件、目录、符号链接是否存在

使用-x , !-x 检查一个文件是否可执行

if指令实例

 if ($http_user_agent ~ MSIE) {             

     rewrite ^(.*)$ /msie/$1 break;

 }

 if ($http_cookie ~* "id=([^;]+)(?:;|$)") {

     set $id $1;

 }

 if ($request_method = POST) {

     return 405;

 }

 if ($slow) {

     limit_rate 10k;

 }

2)return指令

用于完成对请求的处理,直接给客户端返回状态码,改指令后所有的nginx配置都是无效的,

语法:return code;

return code URL;

return URL;

默认值:无

作用域:server,location,if

3)set指令

 

语法:set variable value;

默认值:none

作用域:server,location,if

定义一个变量并赋值,值可以是文本,变量或者文本变量混合体。

 

4)uninitialized_variable_warn指令

语法:uninitialized_variable_warn on | off;
默认值:uninitialized_variable_warn on
作用域:http,server,location,if
控制是否输出为初始化的变量到日志

5)rewrite指令

该指令通过正则来改变url,可以同时存在一个或者多个指令

语法:rewrite regex replacement [flag];

默认值:无

作用域:server,location,if

regex :用于匹配uri的正则表达式。使用括号()标记要截取的内容

replacement 匹配成功后用于替换uri中被截取内容的字符串,默认情况下,如果该字符串是由http://或者https://开头的,则不会继续向下对uri进行其他处理,而是直接将重写后的uri返回给客户端

flag 用来设置rewrite对uri的处理行为,常用的有

    last 停止处理后续rewrite指令集,然后对当前重写的新URI在rewrite指令集上重新查找。

break 停止处理后续rewrite指令集,并不在重新查找,但是当前location内剩余非rewrite语句和location外的的非rewrite语句可以执行。

redirect 如果replacement不是以http:// 或https://开始,返回302临时重定向

permant 返回301永久重定向

 补充:last和break标记的区别在于,last标记在本条rewrite规则执行完后,会对其所在的server { … } 标签重新发起请求,而break标记则在本条规则匹配完成后,停止匹配,不再做后续的匹配。另外有些时候必须使用last,比如在使用alias指令时,而 使用proxy_pass指令时则必须使用break。

注意:rewrite 规则优先级要高于location,在nginx配置文件中,nginx会先用rewrite来处理url,最后再用处理后的url匹配location

6)常用的变量

$args : #这个变量等于请求行中的参数,同$query_string

$content_length : 请求头中的Content-length字段。

$content_type : 请求头中的Content-Type字段。

$document_root : 当前请求在root指令中指定的值。

$host : 请求主机头字段,否则为服务器名称。

$http_user_agent : 客户端agent信息

$http_cookie : 客户端cookie信息

$limit_rate : 这个变量可以限制连接速率。

$request_method : 客户端请求的动作,通常为GET或POST。

$remote_addr : 客户端的IP地址。

$remote_port : 客户端的端口。

$remote_user : 已经经过Auth Basic Module验证的用户名。

$request_filename : 当前请求的文件路径,由root或alias指令与URI请求生成。

$scheme : HTTP方法(如http,https)。

$server_protocol : 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。

$server_addr : 服务器地址,在完成一次系统调用后可以确定这个值。

$server_name : 服务器名称。

$server_port : 请求到达服务器的端口号。

$request_uri : 包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”。

$uri : 不带请求参数的当前URI,$uri不包含主机名,如”/foo/bar.html”。

$document_uri : 与$uri相同。

7)常用正则:

. : 匹配除换行符以外的任意字符

? : 重复0次或1次

+ : 重复1次或更多次

* : 重复0次或更多次

d :匹配数字

^ : 匹配字符串的开始

$ : 匹配字符串的介绍

{n} : 重复n次

{n,} : 重复n次或更多次

[c] : 匹配单个字符c

[a-z] : 匹配a-z小写字母的任意一个

小括号()之间匹配的内容,可以在后面通过$1来引用,$2表示的是前面第二个()里的内容。正则里面容易让人困惑的是转义特殊字符。

 

配置案例

1. 在URL结尾添加斜杠

在虚拟主机中这么添加一条改写规则:

  1. rewrite ^(.*[^/])$ $1/ permanent;

2. 删除URL结尾的斜杠

在虚拟主机中这么添加一条改写规则:

  1. rewrite ^/(.*)//$1 permanent;
-ldl -lpthread -lcrypt -lpcre -lssl -lcrypto -ldl -lpthread -lz 
-Wl,-E
sed -e "s|%%PREFIX%%|/usr/local/nginx|" 
    -e "s|%%PID_PATH%%|/usr/local/nginx/logs/nginx.pid|" 
    -e "s|%%CONF_PATH%%|/usr/local/nginx/conf/nginx.conf|" 
    -e "s|%%ERROR_LOG_PATH%%|/usr/local/nginx/logs/error.log|" 
    < man/nginx.8 > objs/nginx.8
make[1]: 离开目录“/usr/local/nginx-1.14.2”
test -d '/usr/local/nginx' || mkdir -p '/usr/local/nginx'
test -d '/usr/local/nginx/sbin' 
    || mkdir -p '/usr/local/nginx/sbin'
test ! -f '/usr/local/nginx/sbin/nginx' 
    || mv '/usr/local/nginx/sbin/nginx' 
        '/usr/local/nginx/sbin/nginx.old'
cp objs/nginx '/usr/local/nginx/sbin/nginx'
test -d '/usr/local/nginx/conf' 
    || mkdir -p '/usr/local/nginx/conf'
cp conf/koi-win '/usr/local/nginx/conf'
cp conf/koi-utf '/usr/local/nginx/conf'
cp conf/win-utf '/usr/local/nginx/conf'
test -f '/usr/local/nginx/conf/mime.types' 
    || cp conf/mime.types '/usr/local/nginx/conf'
cp conf/mime.types '/usr/local/nginx/conf/mime.types.default'
test -f '/usr/local/nginx/conf/fastcgi_params' 
    || cp conf/fastcgi_params '/usr/local/nginx/conf'
cp conf/fastcgi_params 
    '/usr/local/nginx/conf/fastcgi_params.default'
test -f '/usr/local/nginx/conf/fastcgi.conf' 
    || cp conf/fastcgi.conf '/usr/local/nginx/conf'
cp conf/fastcgi.conf '/usr/local/nginx/conf/fastcgi.conf.default'
test -f '/usr/local/nginx/conf/uwsgi_params' 
    || cp conf/uwsgi_params '/usr/local/nginx/conf'
cp conf/uwsgi_params 
    '/usr/local/nginx/conf/uwsgi_params.default'
test -f '/usr/local/nginx/conf/scgi_params' 
    || cp conf/scgi_params '/usr/local/nginx/conf'
cp conf/scgi_params 
    '/usr/local/nginx/conf/scgi_params.default'
test -f '/usr/local/nginx/conf/nginx.conf' 
    || cp conf/nginx.conf '/usr/local/nginx/conf/nginx.conf'
cp conf/nginx.conf '/usr/local/nginx/conf/nginx.conf.default'
test -d '/usr/local/nginx/logs' 
    || mkdir -p '/usr/local/nginx/logs'
test -d '/usr/local/nginx/logs' 
    || mkdir -p '/usr/local/nginx/logs'
test -d '/usr/local/nginx/html' 
    || cp -R html '/usr/local/nginx'
test -d '/usr/local/nginx/logs' 
    || mkdir -p '/usr/local/nginx/logs'
原文地址:https://www.cnblogs.com/linuxws/p/10588156.html