• Nginx配置


    一、Nginx编译安装
    yum -y install autoconf pcre pcre-devel zlib zlib-devel openssl openssl-devel libtool
    wget http://nginx.org/download/nginx-1.14.2.tar.gz #Stable version为最新稳定版
    useradd nginx -s /sbin/nologin -M
    ./configure --prefix=/application/nginx-1.14.2 --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre
    make && make install
    ln -s /application/nginx-1.14.2 /application/nginx     #创建软链接
    /application/nginx-1.14.2/sbin/nginx
    /application/nginx-1.14.2/sbin/nginx -s stop
    /application/nginx-1.14.2/sbin/nginx -s reload

    二、修改或隐藏Nginx版本号
    [root@lb01 ~]# vim tools/nginx-1.14.2/src/core/nginx.h

    1
    2 /*
    3 * Copyright (C) Igor Sysoev
    4 * Copyright (C) Nginx, Inc.
    5 */
    6
    7
    8 #ifndef _NGINX_H_INCLUDED_
    9 #define _NGINX_H_INCLUDED_
    10
    11
    12 #define nginx_version 1014002
    13 #define NGINX_VERSION "2.4.32" 
    14 #define NGINX_VER "apache/" NGINX_VERSION
    15
    16 #ifdef NGX_BUILD
    17 #define NGINX_VER_BUILD NGINX_VER " (" NGX_BUILD ")"
    18 #else
    19 #define NGINX_VER_BUILD NGINX_VER
    20 #endif
    21
    22 #define NGINX_VAR "NGINX"
    23 #define NGX_OLDPID_EXT ".oldbin"
    24
    25
    26 #endif /* _NGINX_H_INCLUDED_ */

    修改第13和14行标红的部份,然后再编译安装。只隐藏nginx版本号在http区块里加上"server_tokens off;"
    注意二者不可同时使用否则只有"server_tokens off;"生效
    http {
    include mime.types;
    default_type application/octet-stream;
    server_tokens off;
    expires 5s;
    sendfile on;
    keepalive_timeout 65;
    }

    三、Nginx全局变量

    $args                    #请求中的参数值
    $query_string            #同 $args
    $arg_NAME                #GET请求中NAME的值
    $is_args                 #如果请求中有参数,值为"?",否则为空字符串
    $uri                     #请求中的当前URI(不带请求参数,参数位于$args),可以不同于浏览器传递的$request_uri的值,它可以通过内部重定向,或者使用index指令进行修改,$uri不包含主机名,如"/foo/bar.html"。
    $document_uri            #同 $uri
    $document_root           #当前请求的文档根目录或别名
    $host                    #优先级:HTTP请求行的主机名>"HOST"请求头字段>符合请求的服务器名
    $hostname                #主机名
    $https                   #如果开启了SSL安全模式,值为"on",否则为空字符串。
    $binary_remote_addr      #客户端地址的二进制形式,固定长度为4个字节
    $body_bytes_sent         #传输给客户端的字节数,响应头不计算在内;这个变量和Apache的mod_log_config模块中的"%B"参数保持兼容
    $bytes_sent              #传输给客户端的字节数
    $connection              #TCP连接的序列号
    $connection_requests     #TCP连接当前的请求数量
    $content_length          #"Content-Length" 请求头字段
    $content_type            #"Content-Type" 请求头字段
    $cookie_name             #cookie名称
    $limit_rate              #用于设置响应的速度限制
    $msec                    #当前的Unix时间戳
    $nginx_version           #nginx版本
    $pid                     #工作进程的PID
    $pipe                    #如果请求来自管道通信,值为"p",否则为"."
    $proxy_protocol_addr     #获取代理访问服务器的客户端地址,如果是直接访问,该值为空字符串
    $realpath_root           #当前请求的文档根目录或别名的真实路径,会将所有符号连接转换为真实路径
    $remote_addr             #客户端地址
    $remote_port             #客户端端口
    $remote_user             #用于HTTP基础认证服务的用户名
    $request                 #代表客户端的请求地址
    $request_body            #客户端的请求主体:此变量可在location中使用,将请求主体通过proxy_pass,fastcgi_pass,uwsgi_pass和scgi_pass传递给下一级的代理服务器
    $request_body_file       #将客户端请求主体保存在临时文件中。文件处理结束后,此文件需删除。如果需要之一开启此功能,需要设置client_body_in_file_only。如果将次文件传递给后端的代理服务器,需要禁用request body,即设置proxy_pass_request_body off,fastcgi_pass_request_body off,uwsgi_pass_request_body off,or scgi_pass_request_body off
    $request_completion      #如果请求成功,值为"OK",如果请求未完成或者请求不是一个范围请求的最后一部分,则为空
    $request_filename        #当前连接请求的文件路径,由root或alias指令与URI请求生成
    $request_length          #请求的长度 (包括请求的地址,http请求头和请求主体)
    $request_method          #HTTP请求方法,通常为"GET""POST"
    $request_time            #处理客户端请求使用的时间; 从读取客户端的第一个字节开始计时
    $request_uri             #这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看$uri更改或重写URI,不包含主机名,例如:"/cnphp/test.php?arg=freemouse"
    $scheme                  #请求使用的Web协议,"http""https"
    $server_addr             #服务器端地址,需要注意的是:为了避免访问linux系统内核,应将ip地址提前设置在配置文件中
    $server_name             #服务器名
    $server_port             #服务器端口
    $server_protocol         #服务器的HTTP版本,通常为 "HTTP/1.0""HTTP/1.1"
    $status                  #HTTP响应代码
    $time_iso8601            #服务器时间的ISO 8610格式
    $time_local              #服务器时间(LOG Format 格式)
    $cookie_NAME             #客户端请求Header头中的cookie变量,前缀"$cookie_"加上cookie名称的变量,该变量的值即为cookie名称的值
    $http_NAME               #匹配任意请求头字段;变量名中的后半部分NAME可以替换成任意请求头字段,如在配置文件中需要获取http请求头:"Accept-Language",$http_accept_language即可
    $http_cookie
    $http_post
    $http_referer
    $http_user_agent
    $http_x_forwarded_for
    $sent_http_NAME          #可以设置任意http响应头字段;变量名中的后半部分NAME可以替换成任意响应头字段,如需要设置响应头Content-length,$sent_http_content_length即可
    $sent_http_cache_control
    $sent_http_connection
    $sent_http_content_type
    $sent_http_keep_alive
    $sent_http_last_modified
    $sent_http_location
    $sent_http_transfer_encoding

    自定义http头部信息,反向代理端配置

    server {
            listen       80;
            server_name  localhost;
    
            #charset koi8-r;
    
            access_log  logs/host.access.log  main;
            
    #underscores_in_headers off; #有些版本使用abc_abc写法可能需要开启该选项,1.14.2版本该选项不起作用
    #underscores_in_headers on;
    location
    / { root html; index index.html index.htm; } location ~ .* { proxy_pass http://10.47.39.8; proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; proxy_set_header abc-abc 'hello world'; #注意abc_abc这种写法没有结果 } }

    web服务器端配置

    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" "$http_abc_abc"';
        sendfile        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        #gzip  on;
    
        server {
            listen       80;
            server_name  localhost;
    
            #charset koi8-r;
    
            access_log  logs/host.access.log  main;
    
            location / {
                root   html;
                index  index.html index.htm;
            }
        }
    }

    [root@nginx nginx-1.14.2]#cat logs/host.access.log
    10.47.39.5 - - [22/Dec/2018:09:26:57 +0800] "GET / HTTP/1.0" 304 0 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" "10.47.254.11" "hello world"

    四、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"';
        sendfile        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        #gzip  on;
    
        server {
            listen       80;
            server_name  localhost;
    
            #charset koi8-r;
    
            access_log  logs/host.access.log  main;
    
            location / {
                root   html;
                index  index.html index.htm;
                add_header Hello_H   'hello';
                add_header world-w   'world';
            }
        }
    }

    五、rewrite模块
    Nginx提供的全局变量或自己设置的变量,结合正则表达式和标志位实现url重写以及重定向
    rewrite只能放在server{},location{},if{}中,并且只能对域名后边的除去传递的参数外的字符串起作用。
    Rewrite主要的功能就是实现URL的重写,Nginx的Rewrite规则采用Pcre,perl兼容正则表达式的语法规则匹配,如果需要Nginx的Rewrite功能,在编译Nginx之前,需要编译安装PCRE库。
    通过Rewrite规则,可以实现规范的URL、根据变量来做URL转向及选择配置
    语法
    rewrite   <regex>   <replacement>   [flag];
    关键字      规则          定向路径       flag标记
    规则:可以是字符串或者perl正则来表示想匹配的url
    定向路径:表示匹配到规则后要定向的路径,如果规则里有分组,则可以使用$1来获取括号中的字符串(可以有多个分组)
    flag标记类型:
    last
    1、结束当前的请求处理,用替换后的URI重新匹配location,可理解为重写(rewrite)后,发起了一个新请求,进入server模块,匹配location;
    2、如果重新匹配循环的次数超过10次,nginx会返回500错误;
    3、返回302 http状态码,浏览器地址栏显示重地向后的url
    break
    1、结束当前的请求处理,使用当前资源,不在执行location里余下的语句;
    2、返回302 http状态码,浏览器地址栏显示重地向后的url
    redirect
    1、临时跳转,返回302 http状态码;
    2、浏览器地址栏显示重地向后的url
    permanent
    1、永久跳转,返回301 http状态码;
    2、浏览器地址栏显示重定向后的url
    示例:
    rewrite ^/(.*) https://www.baidu.com/$1 break;

    六、Nginx if判断语法
    if (表达式) {
    }
    当表达式只是一个变量时,如果值为空或任何以0开头的字符串都会当做false
    直接比较变量和内容是否相等时,使用=或!=
    ~区分大小写的正则表达式匹配,~*不区分大小写的匹配,!~区分大小写的不匹配
    一些内置的条件判断:
    -f和!-f用来判断是否存在文件
    -d和!-d用来判断是否存在目录
    -e和!-e用来判断是否存在文件或目录
    -x和!-x用来判断文件是否可执行
    示例:
    location ~ /.* {
         if ($http_user_agent ~* chrome ) { 
                return 403;       #只能return Http状态码
         }
    }

    七、Nginx日志格式说明
    $remote_addr, $http_x_forwarded_for  记录客户端IP地址
    $remote_user     记录客户端用户名称
    $request      记录请求的URL和HTTP协议
    $status     记录请求状态
    $body_bytes_sent   发送给客户端的字节数,不包括响应头的大小; 该变量与Apache模块mod_log_config里的“%B”参数兼容。
    $bytes_sent   发送给客户端的总字节数。
    $connection    连接的序列号。
    $connection_requests   当前通过一个连接获得的请求数量。
    $msec   日志写入时间。单位为秒,精度是毫秒。
    $pipe   如果请求是通过HTTP流水线(pipelined)发送,pipe值为“p”,否则为“.”。
    $http_referer   记录从哪个页面链接访问过来的
    $http_user_agent   记录客户端浏览器相关信息
    $request_length   请求的长度(包括请求行,请求头和请求正文)。
    $request_time   请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始,直到把最后一个字符发送给客户端后进行日志写入为止。
    $time_iso8601   ISO8601标准格式下的本地时间。
    $time_local   通用日志格式下的本地时间。

    八、Nginx配置文件

    #定义Nginx运行的用户和用户组
    user www www;
    
    #nginx进程数,建议设置为等于CPU总核心数。
    worker_processes 4;
    
    #全局错误日志类型定义,[ debug | info | notice | warn | error | crit ]
    error_log /var/log/nginx/error.log info;
    
    #进程pid文件
    pid /var/run/nginx.pid;
    
    #一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。
    worker_rlimit_nofile 65535;
    
    #工作模式与连接数上限
    events
    {
    #参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
    use epoll;
    #单个进程最大连接数(最大连接数=连接数*进程数)
    worker_connections 65535;
    }
    
    http {
    include mime.types; #文件扩展名与文件类型映射表
    default_type application/octet-stream; #默认文件类型
    #charset utf-8; #默认编码
    server_names_hash_bucket_size 128; #服务器名字的hash表大小
    client_header_buffer_size 32k; #上传文件大小限制
    large_client_header_buffers 4 64k; #设定请求缓
    client_max_body_size 8m; #设定请求缓
    sendfile on; #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
    autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。
    tcp_nopush on; #防止网络阻塞
    tcp_nodelay on; #防止网络阻塞
    keepalive_timeout 120; #长连接超时时间,单位是秒
    
    #FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    
    #gzip模块设置
    gzip on; #开启gzip压缩输出
    gzip_min_length 1k; #最小压缩文件大小
    gzip_buffers 4 16k; #压缩缓冲区
    gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
    gzip_comp_level 2; #压缩等级
    gzip_types text/plain application/x-javascript text/css application/xml;
    #压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。
    gzip_vary on;
    #limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用
    
    upstream blog.ha97.com {
    #upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。
    server 192.168.80.121:80 weight=3;
    server 192.168.80.122:80 weight=2;
    server 192.168.80.123:80 weight=3;
    }
    
    server {
    #监听端口
    listen 80;
    #域名可以有多个,用空格隔开
    server_name www.ha97.com ha97.com;
    index index.html index.htm index.php;
    root /data/www/ha97;
    location ~ .*.(php|php5)?$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi.conf;
    }
    
    #日志格式设定
    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/ha97access.log main;
    
    #图片缓存时间设置
    location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {
    expires 10d;
    }
    #JS和CSS缓存时间设置
    location ~ .*.(js|css)?$ {
    expires 1h;
    }
    
    #对 "/" 启用反向代理
    location / {
    proxy_pass http://127.0.0.1:88;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
    proxy_set_header Host $host;
    client_max_body_size 10m; #允许客户端请求的最大单文件字节数
    }
    
    #设定查看Nginx状态的地址
    location = /status/ {
    stub_status on;
    access_log on;
    auth_basic "NginxStatus";
    auth_basic_user_file conf/htpasswd;
    #htpasswd文件的内容可以用apache提供的htpasswd工具来产生。
    }
    View Code

    九、返回状态码是404时,重定向到https://www.baidu.com

    location / {
       root html;
       index index.html;
    }
    #error_page  404 https://www.baidu.com;  #1.18.0版本支持该写法
    error_page 404 = @fallback;
    location @falldback {
       proxy_pass https://www.baidu.com;
    }

    参考链接:
            https://www.cnblogs.com/lidabo/p/4169396.html     #Nginx之location匹配规则
            https://www.cnblogs.com/jsonhc/p/7199295.html?utm_source=itdadao&utm_medium=referral    #nginx之配置proxy_set_header

  • 相关阅读:
    php 通过header下载中文文件名 压缩包损坏或文件不存在的问题
    MySQL查看数据库安装路径
    PHP 中move_uploaded_file 上传中文文件名失败
    C# Windows异步I/O操作
    .Net 环境下比较各种数据库插入操作的性能
    GenericFactoryMethod泛型工厂模式实现简单IOC功能
    State状态模式
    .Net RabbitMQ之消息通信 构建RPC服务器
    .Net RabbitMQ系列之环境搭建于RabbitMQ基本介绍
    C# 算法之选择排序
  • 原文地址:https://www.cnblogs.com/xwupiaomiao/p/10149654.html
Copyright © 2020-2023  润新知