安装

  1. # 1. 基础环境
  2. useradd -r -s /sbin/nologin -M www ##创建nginx用户
  3. yum install -y gcc gcc-c++ glibc glibc-devel pcre pcre-devel zlib zlib-devel openssl openssl-devel
  4. # 2. 下载
  5. wget https://nginx.org/download/nginx-1.22.0.tar.gz
  6. # 3. 解压
  7. tar -xf /work/packages/nginx-1.22.0.tar.gz
  8. # 4. 编译安装nginx---#echo $?查看是否出错
  9. cd /work/packages/nginx-1.22.0
  10. ./configure --prefix=/usr/local/nginx --user=www --with-http_stub_status_module --with-http_ssl_module
  11. make && make install
  12. # 5. 设置systemd管理
  13. ln -s /usr/local/nginx/sbin/* /sbin/
  14. cp /work/config/nginx/nginx.service /usr/lib/systemd/system/
  15. # 6. 配置nginx
  16. \cp -f /work/config/nginx/nginx.conf /usr/local/nginx/conf/
  17. mkdir -p /usr/local/nginx/conf/vhost/ && \cp -f /work/config/nginx/default.conf /usr/local/nginx/conf/vhost/
  18. # 6. 启动nginx
  19. systemctl enable --now nginx
  20. #7. 测试
  21. ps -ef |grep nginx
  22. ss -antl |grep :80
  23. mkdir -p /data/{baidu,jd}
  24. echo "nginx install successful" /data/baidu/index.html
  25. echo -e "<?php\n phpinfo(); \n?>" /data/baidu/index.php
  26. echo "127.0.0.1 www.baidu.com www.jd.com" >> /etc/hosts
  27. curl www.baidu.com
  28. curl www.jd.com
  1. [Unit]
  2. Description=nginx - high performance web server
  3. Documentation=http://nginx.org/en/docs/
  4. After=network-online.target remote-fs.target nss-lookup.target
  5. Wants=network-online.target
  6. [Service]
  7. Type=forking
  8. PIDFile=/usr/local/nginx/logs/nginx.pid
  9. ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
  10. ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /usr/local/nginx/run/nginx.pid)"
  11. ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /usr/local/nginx/run/nginx.pid)"
  12. WantedBy=multi-user.target

配置文件

  1. #user nobody;
  2. worker_processes 1;
  3. #error_log logs/error.log;
  4. #error_log logs/error.log notice;
  5. #error_log logs/error.log info;
  6. #pid logs/nginx.pid;
  7. events {
  8. worker_connections 1024;
  9. }
  10. http {
  11. include mime.types;
  12. default_type application/octet-stream;
  13. #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  14. # '$status $body_bytes_sent "$http_referer" '
  15. # '"$http_user_agent" "$http_x_forwarded_for"';
  16. #access_log logs/access.log main;
  17. sendfile on;
  18. #tcp_nopush on;
  19. #keepalive_timeout 0;
  20. keepalive_timeout 65;
  21. #gzip on;
  22. server {
  23. listen 80;
  24. server_name localhost;
  25. #charset koi8-r;
  26. #access_log logs/host.access.log main;
  27. location / {
  28. root html;
  29. index index.html index.htm;
  30. }
  31. #error_page 404 /404.html;
  32. # redirect server error pages to the static page /50x.html
  33. #
  34. error_page 500 502 503 504 /50x.html;
  35. location = /50x.html {
  36. root html;
  37. }
  38. # proxy the PHP scripts to Apache listening on 127.0.0.1:80
  39. #
  40. #location ~ \.php$ {
  41. # proxy_pass http://127.0.0.1;
  42. #}
  43. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  44. #
  45. #location ~ \.php$ {
  46. # root html;
  47. # fastcgi_pass 127.0.0.1:9000;
  48. # fastcgi_index index.php;
  49. # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  50. # include fastcgi_params;
  51. #}
  52. # deny access to .htaccess files, if Apache's document root
  53. # concurs with nginx's one
  54. #
  55. #location ~ /\.ht {
  56. # deny all;
  57. #}
  58. }
  59. # another virtual host using mix of IP-, name-, and port-based configuration
  60. #
  61. #server {
  62. # listen 8000;
  63. # listen somename:8080;
  64. # server_name somename alias another.alias;
  65. # location / {
  66. # root html;
  67. # index index.html index.htm;
  68. # }
  69. #}
  70. # HTTPS server
  71. #
  72. #server {
  73. # listen 443 ssl;
  74. # server_name localhost;
  75. # ssl_certificate cert.pem;
  76. # ssl_certificate_key cert.key;
  77. # ssl_session_cache shared:SSL:1m;
  78. # ssl_session_timeout 5m;
  79. # ssl_ciphers HIGH:!aNULL:!MD5;
  80. # ssl_prefer_server_ciphers on;
  81. # location / {
  82. # root html;
  83. # index index.html index.htm;
  84. # }
  85. #}
  86. }
  1. 分类 分类描述
  2. 1** 信息,服务器收到请求,需要请求者继续执行操作
  3. 2** 成功,操作被成功接收并处理
  4. 200 - 请求成功
  5. 3** 重定向,需要进一步的操作以完成请求
  6. 301 - 资源(网页等)被永久转移到其它URL
  7. 4** 客户端错误,请求包含语法错误或无法完成请求
  8. 401 - 请求要求用户的身份认证
  9. 403 - 拒绝执行此请求
  10. 404 - 请求的资源(网页等)不存在
  11. 408 - 服务器等待客户端发送的请求时间过长,超时
  12. 5** 服务器错误,服务器在处理请求的过程中发生了错误
  13. 500 - 内部服务器错误
  14. 503 - 由于超载或系统维护,服务器暂时的无法处理客户端的请求。延时的长度可包含在服务器的Retry-After头信息中
  15. 504 - 充当网关或代理的服务器,未及时从远端服务器获取请求
  1. # Nginx日志结构
  2. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  3. '$status $body_bytes_sent "$http_referer" '
  4. '"$http_user_agent" $request_time';
  5. $remote_addr 记录客户端IP地址
  6. $http_host 请求地址,即浏览器中你输入的地址(IP或域名)
  7. $server_name 虚拟主机名称
  8. $http_x_forwarded_for HTTP请求端真实的IP
  9. $time_local 记录了当前日志条目的时间
  10. $remote_user 记录请求客户端用户名称
  11. $request 记录请求的URLHTTP协议
  12. $status 记录返回HTTP请求的状态
  13. $uptream_status uptream的状态
  14. $ssl_protocol SSL协议版本
  15. $body_bytes_sent 发送给客户端的字节数,不包括响应头的大小
  16. $bytes_sent 发送给客户端的总字节数
  17. $connection_requests 当前通过一个连接获得的请求数量
  18. $http_referer 记录从哪个页面链接访问过来的
  19. $http_user_agent 记录客户端浏览器相关信息
  20. $request_length 请求的长度,包括请求行,请求头和请求正文
  21. $msec 日志写入时间
  22. $request_time 请求处理时间
  23. $upstream_response_time 应用程序响应时间
=        修饰符:要求路径完全匹配
~        修饰符:区分大小写的正则匹配
~*       不区分大小写的正则匹配
^~       开头表示uri以某个常规字符串开头,理解为匹配 url路径即可
!~和!~*  分别为区分大小写不匹配及不区分大小写不匹配 的正则
/        任何没有匹配成功的,都会匹配这里处理

制作nginx配置文件

# nginx主配置文件

# 全局配置
user    www;                                # 管理nginx进程的用户
group   www;                                # 管理nginx进程的组
pid     /usr/local/nginx/logs/nginx.pid;        # pid文件存储位置

worker_processes 4;                                          # 工作进程数  取值:CPU的内核数  【cat /proc/cpuinfo | grep processor|wc -l】
worker_cpu_affinity 0001 0010 0100 1000;    # CPU亲和力

error_log /usr/local/nginx/logs/error.log;      # 错误日志(错误日志级别: debug info notice warn error crit)



# 事件处理机制(工作模式)
events{
    use epoll;                              # 工作模式为epoll(异步非阻塞)
    worker_connections 65535;               # 工作进程的最大连接数量
    multi_accept on;                                                # 尽可能多地接受请求(连接多的时候打开,连接不多则不用打开)
}


# http模块从外到内有http块(1个)、server块(n个)、location块(n个)
http {
      # 设置MIME类型,类型由mime.type文件定义
      include         mime.types;
    default_type    application/octet-stream;

    # 隐藏nginx版本
    server_tokens off;

    # 设置日志格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" $request_time';
    log_format  test  '$remote_addr';



    # 日志切割通过时间  格式:access-2022-06-26.log
    map $time_iso8601 $logdate {
    '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
    default    'date-not-found';
    }
    assess_log /usr/local/nginx/logs/access.log;            # 访问日志存储位置
    # access_log logs/80/access-$logdate.log;


    # 开启高效文件传输模式
    sendfile   on;
    tcp_nopush on;
    tcp_nodelay on;
    server_names_hash_bucket_size 128;
    server_names_hash_max_size 512;
    keepalive_timeout  65;
    send_timeout 60s;


    # 开启gzip压缩
    gzip on;
    gzip_min_length   2k;
    gzip_buffers      4 16k;
    gzip_http_version 1.1;
    gzip_comp_level   4;                                   # 压缩级别,最大9-1 压缩后比例越小,cpu处理更快
    gzip_types        text/plain application/x-javascript text/css application/xml;   # 指定压缩类型,(conf/mime.types)
    gzip_vary         on;


    # fastcgi调优 (PHP连接)
    #时间超时设定
    fastcgi_connect_timeout 240;
    fastcgi_send_timeout 240;
    fastcgi_read_timeout 240;
    #缓冲/缓存设置
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    # fastcgi_temp_path /data/ngx_fcgi_tmp;
    # fastcgi_cache_path /data/ngx_fcgi_cache levels=2:2 keys_zone=ngx_fcgi_cache:512m inactive=1d max_size=40g;


    # 客户端缓存
    client_max_body_size       10m;                    # 允许客户端请求的 最大单文件 字节数
    client_body_buffer_size    128k;                    # 缓冲区代理缓冲用户端请求最大字节数
    client_header_buffer_size  4k;                        # 客户端请求头缓冲大小(一般一个请求头不超过1KB)
    large_client_header_buffers 4 4k;                # 设置请求缓冲

    # 代理缓存
    proxy_connect_timeout 90;                                    # nginx与后端服务器,连接超时时间(代理连接超时)
    proxy_send_timeout    90;                                    # 后端服务器与nginx,数据传回时间(代理发送超时)
    proxy_read_timeout    90;                                    # 连接后,与后端服务器响应时间(代理接收超时)
    proxy_buffer_size     4k;                                # 设置nginx保存用户头信息的缓冲区大小
    proxy_buffers       4 32k;                                # 缓冲区[申请4个单位为32KB的内存]
    # proxy_busy_buffers_size 64k;                        # 如果网页平均在32KB以下可以设置

    # 加载配置文件
    include vhost/*.conf;
}
# 1. 浏览目录
server {
    listen 8001;
    server_name www.sand.com;
    access_log logs/8001/access-$logdate.log test;           # mkdir logs/8001/ && chown -R www.www 8001
    # error_log  logs/8001/error-$logdate.log notice;

    location /map {
        root /home/map/www/;                                  # 指定目录所在路径
        autoindex on;                                                                        # 开启目录列表访问(可以下载文件)
        autoindex_format html;                                # 以html风格将目录展示在浏览器中
        autoindex_exact_size off;                             # 切换为 off 后,以可读的方式显示文件大小,单位为 KB、MB 或者 GB
        autoindex_localtime on;                               # 以服务器的文件时间作为显示的时间
        charset utf-8,gbk;                                    # 展示中文文件名
    }
}


# 2. Nginx+PHP网页配置   以及   fastcgi优化 php
server {
    listen 8002;
    server_name www.sand.com;

    location ~ \.php$ {
        root           /usr/local/nginx/html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        include        fastcgi_params;

        #FastCGI 相关参数调优
        fastcgi_cache_valid 200 302 1h;
        fastcgi_cache_valid 301 1d;
        fastcgi_cache_valid any 1m;
        fastcgi_cache_min_uses 1;
        fastcgi_cache_use_stale error timeout invalid_header http_500;
        fastcgi_cache_key http://$host$request_uri;
  }


# 3. Nginx+jsp网页配置
server {
  listen 8003;
  server_name www.sand.com;
  root /usr/local/nginx/html;
  index index.jsp index.html;

  location / {
    proxy_next_upstream http_502 http_504 error timeout invalid_header;
    proxy_set_header Host $host
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwaeded-For $proxy_add_x_forwaeded_for;
  }
}

# 4. 反向代理配置
server {
   listen 8004;
   server_name www.sand.com;
   root /usr/local/nginx/html;

   location / {
       proxy_pass http://www.baidu.com
   }
}

# 5. 负载均衡反向代理配置
upstream bbs {
    # weight 权重   
    # max_fails 如果后端同一个节点不可用,那么接将把节点标记为不可用
    # fail_timeout 一个周期,再一次去请求
    server 192.168.10.101 weight=1 max_fails=2 fail_timeout=30s;
    server 192.168.10.102 weight=1 max_fails=2 fail_timeout=30s;
}
server {
   listen 8005;
   server_name www.sand.com;
   root /usr/local/nginx/html;

   location / {
     proxy_pass http://bbs;
     proxy_set_header Host $host;    # 重写请求头部 proxy_set_header X-Forwarded-For $remote_addr;
   }
}


# 6. 优化,浏览器缓存,防盗链设置
server {
    listen 8006;
    server_name www.sand.com;

    # 0. 网页文件
    location / {
        root /usr/local/nginx/html;
        index   index.html;
    }
    # 1-2. 设置客户端浏览器缓存,防盗链设置
    location ~* \.(css|js|png|jpg|jpeg|gif|gz|svg|mp4|ogg|ogv|webm|htc|xml|woff)$ {
        access_log off;
        # 1. 设置客户端浏览器缓存
        expires 30d;
        # 2. 防盗链设置
        valid_referers www.sand.com;
        if ($invalid_referer) {
            return 403;
                  break;
        }
    }
    # 3. 开启status状态
    location /nginx_status {
        stub_status on;
        access_log off;
    }
    # 4. 设置白名单黑名单
    location /nginx {
        allow   192.168.0.0/24;   # 白名单(允许访问)
        deny    all;              # 黑名单(拒绝访问)
    }
}
############ 虚拟主机配置 #############
    # 虚拟主机配置【基于IP, 基于PORT,基于host】
    # 虚拟主机配置【基于网卡,基于端口,基于域名】
        IP-ens33:  listen 192.168.11.11:80;
        IP-ens37:  listen 192.168.22.11:80;
        端口:      listen 80;
        端口:      listen 81;
        域名:      server_name host1;
        域名:      server_name host2;
    # /usr/local/nginx/conf/vhost/www1.conf
    server {
      listen 80;
      server_name www.sand1.com;
      access_log logs/sand1.access.log;

      location / {
        root html/www1;
        index index.html index.htm;
      }
    }
    # /usr/local/nginx/conf/vhost/www2.conf
    server {
      listen 80;
      server_name www.sand2.com;
      access_log logs/sand2.access.log;

      location / {
        root html/www2;
        index index.html index.htm;
      }
    }
# WEB--nginx内核优化
fs.file-max = 999999:这个参数表示进程(比如一个worker进程)可以同时打开的最大句柄数,这个参数直线限制最大并发连接数,需根据实际情况配置。
net.ipv4.tcp_max_tw_buckets = 6000 :这个参数表示操作系统允许TIME_WAIT套接字数量的最大值,如果超过这个数字,TIME_WAIT套接字将立刻被清除并打印警告信息。该参数默认为180000,过多的TIME_WAIT套接字会使Web服务器变慢。注:主动关闭连接的服务端会产生TIME_WAIT状态的连接
net.ipv4.ip_local_port_range = 1024 65000  :允许系统打开的端口范围。
net.ipv4.tcp_tw_recycle = 1 :启用timewait快速回收。
net.ipv4.tcp_tw_reuse = 1 :开启重用。允许将TIME-WAIT sockets重新用于新的TCP连接。这对于服务器来说很有意义,因为服务器上总会有大量TIME-WAIT状态的连接。
net.ipv4.tcp_keepalive_time = 30:这个参数表示当keepalive启用时,TCP发送keepalive消息的频度。默认是2小时,若将其设置的小一些,可以更快地清理无效的连接。
net.ipv4.tcp_syncookies = 1 :开启SYN Cookies,当出现SYN等待队列溢出时,启用cookies来处理。
net.core.somaxconn = 40960  :web 应用中 listen 函数的 backlog 默认会给我们内核参数的。
net.core.somaxconn  :限制到128,而nginx定义的NGX_LISTEN_BACKLOG 默认为511,所以有必要调整这个值。注:对于一个TCP连接,Server与Client需要通过三次握手来建立网络连接.当三次握手成功后,我们可以看到端口的状态由LISTEN转变为ESTABLISHED,接着这条链路上就可以开始传送数据了.每一个处于监听(Listen)状态的端口,都有自己的监听队列.监听队列的长度与如somaxconn参数和使用该端口的程序中listen()函数有关。somaxconn定义了系统中每一个端口最大的监听队列的长度,这是个全局的参数,默认值为128,对于一个经常处理新连接的高负载 web服务环境来说,默认的 128 太小了。大多数环境这个值建议增加到 1024 或者更多。大的侦听队列对防止拒绝服务 DoS 攻击也会有所帮助。
net.core.netdev_max_backlog = 262144  :每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包的最大数目。
net.ipv4.tcp_max_syn_backlog = 262144 :这个参数标示TCP三次握手建立阶段接受SYN请求队列的最大长度,默认为1024,将其设置得大一些可以使出现Nginx繁忙来不及accept新连接的情况时,Linux不至于丢失客户端发起的连接请求。
net.ipv4.tcp_rmem = 10240 87380 12582912 :这个参数定义了TCP接受缓存(用于TCP接受滑动窗口)的最小值、默认值、最大值。
net.ipv4.tcp_wmem = 10240 87380 12582912:这个参数定义了TCP发送缓存(用于TCP发送滑动窗口)的最小值、默认值、最大值。
net.core.rmem_default = 6291456:这个参数表示内核套接字接受缓存区默认的大小。
net.core.wmem_default = 6291456:这个参数表示内核套接字发送缓存区默认的大小。
net.core.rmem_max = 12582912:这个参数表示内核套接字接受缓存区的最大大小。
net.core.wmem_max = 12582912:这个参数表示内核套接字发送缓存区的最大大小。
net.ipv4.tcp_syncookies = 1:该参数与性能无关,用于解决TCP的SYN攻击。
控制速度set $limit_rate 1k;
Nginx的http核心模块ngx_http_core_module中提供limit_rate这个指令可以用于控制速度,limit_rate_after用于设置http请求传输多少字节后开始限速。





add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';



if (!-e $request_filename) {
                    rewrite ^/(.*)$ /init.php?s=$1 last;
}
if (!-e $request_filename) {
                        rewrite /admin/(.*)$ /admin.php/$1 last;
                        rewrite /cli/(.*)$ /cli.php/$1 last;
                        rewrite  ^(.*)$  /index.php?s=$1  last;
                        break;
}


fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;


# https
ssl_certificate /etc/nginx/conf.d/cert/djssg-client-test/1_djssg-client-test.anyaojs.com_bundle.crt;
ssl_certificate_key /etc/nginx/conf.d/cert/djssg-client-test/2_djssg-client-test.anyaojs.com.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;