Aldebaran

人生最棒的感觉,就是你做到别人说你做不到的事。

0%

Nginx配置调优

三田寺円

Nginx配置文件结构

  1. 全局块:配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。

  2. events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。

  3. http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。

  4. server块:配置虚拟主机的相关参数,一个http中可以有多个server。

  5. location块:配置请求的路由,以及各种页面的处理情况。

  6. stream块:配置TCP代理。

下面给大家上一个配置文件,作为理解,

线上配置

Nginx主配置文件

  • nginx.conf

      $ sudo vim /usr/local/nginx/conf/nginx.conf
      user                  nginx nginx;
      worker_processes      auto;
    
      ## Binds worker processes to the sets of CPUs.
      ## Each CPU set is represented by a bitmask of allowed CPUs. There should be a separate set defined for each of the worker processes.
      ## By default, worker processes are not bound to any specific CPUs.
      worker_cpu_affinity   auto;
    
      error_log             /var/log/nginx/error.log  notice;
      pid                   /var/run/nginx.pid;
    
      ## Specifies the value for maximum file descriptors that can be opened by this process.
      worker_rlimit_nofile  51200;
    
      events
      {
          use epoll;
    
          ## Sets the maximum number of simultaneous connections that can be opened by a worker process.
          ## It should be kept in mind that this number includes all connections (e.g. connections with proxied servers, among others), not only connections with clients.
          ## Another consideration is that the actual number of simultaneous connections cannot exceed the current limit on the maximum number of open files, which can be changed by worker_rlimit_nofile.
    
          ## maxclient = worker_processes * worker_connections / cpu_number
          worker_connections 30000;
      }
    
      http
      {
          include       mime.types;
          default_type  application/octet-stream;
    
          # log_format    weblog  '$http_x_forwarded_for $remote_port "$request" $status [$time_local] '
          #                        '"$http_user_agent" "$http_referer" $body_bytes_sent '
          #                        '$remote_addr $gzip_ratio';
    
          log_format weblog  '{"time_local":"$time_local",'
              '"http_host":"$http_host",'
              '"remote_addr":"$remote_addr",'
              '"remote_port":"$remote_port",'
              '"remote_user":"$remote_user",'
              '"request":"$request",'
              '"status":"$status",'
              '"request_time":"$request_time",'
              '"request_body":"$request_body",'
              '"body_bytes_sent":"$body_bytes_sent",'
              '"http_referer":"$http_referer",'
              '"upstream_addr":"$upstream_addr",'
              '"upstream_response_time":"$upstream_response_time",'
              '"http_x_forwarded_for":"$http_x_forwarded_for",'
              '"scheme":"$scheme",'
              '"gzip_ratio":"$gzip_ratio",'
              '"http_user_agent":"$http_user_agent"'
          '}';
    
          sendfile           on;
          server_tokens      off;
          tcp_nopush         on;
          tcp_nodelay        on;
          keepalive_timeout  60;
          request_pool_size  4k;
    
          ## Allows accurate tuning of per-connection memory allocations. 
          ## This directive has minimal impact on performance and should not generally be used. 
          ## By default, the size is equal to 256 bytes on 32-bit platforms and 512 bytes on 64-bit platforms.
          connection_pool_size            512;
    
          client_header_timeout           3m;
          client_body_timeout             3m;
          send_timeout                    3m;
          client_header_buffer_size       256k;
          large_client_header_buffers     4 1024k;
          client_max_body_size            10m;
          client_body_buffer_size         256k;
          output_buffers                  4 32k;
          postpone_output                 1460;
          server_names_hash_bucket_size   128;
    
          fastcgi_connect_timeout        180s;
          fastcgi_send_timeout           180s;
          fastcgi_read_timeout           180s;
          fastcgi_buffer_size            2048k;
          fastcgi_buffers                4 1024k;
          fastcgi_busy_buffers_size      2048k;
          fastcgi_temp_file_write_size   2048k;
    
          gzip                  on;
          gzip_http_version     1.1;
          gzip_comp_level       2;
          gzip_min_length       1100;
          gzip_buffers          16 8k;
          gzip_vary             on;
          gzip_proxied          expired no-cache no-store private auth;
          gzip_types            text/plain text/css application/json text/xml application/xml application/xml+rss text/javascript application/javascript application/x-javascript;
    
          ## The following includes are specified for virtual hosts
          include          vhosts/*.conf;
      }
      stream {
          log_format proxy '$remote_addr [$time_local] '
                      '$protocol $status $bytes_sent $bytes_received '
                      '$session_time "$upstream_addr" '
                      '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
    
          # access_log off;
          access_log /var/log/nginx/tcp-access.log proxy ;
          # open_log_file_cache off;
          open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;
    
          include          stream/*.ini;
      }
    

Nginx https配置(这里以 Nginx静态服务配置为例)

  • https.conf

      server {
          listen 80 default_server;
          listen [::]:80 default_server;
    
          # Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response.
          return 301 https://$host$request_uri;
      }
    
      server
      {
          listen  443 ssl default;
          # listen [::]:443 ssl;
    
          server_name XXXX.com www.XXXX.com;
          root  /data/wwwroot/XXXX.com/webroot;
          index index.shtml index.html;
    
          ssl_protocols       TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
          ssl_certificate     /etc/letsencrypt/live/XXXX.com/fullchain.pem;
          ssl_certificate_key /etc/letsencrypt/live/XXXX.com/privkey.pem;
    
          ## Specifies that server ciphers should be preferred over client ciphers when the SSLv3 and TLS protocols are used.
          ssl_prefer_server_ciphers on;
          # ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
          ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS";
    
          ## Diffie-Hellman parameter for DHE ciphersuites, recommended 2048 bits
          ## openssl dhparam -out /usr/local/nginx/sslkey/dh_ssl/nginx_dh_2048.pem 2048
          ssl_dhparam /usr/local/nginx/sslkey/dh_ssl/nginx_dh_2048.pem;
    
          ## The special value auto (1.11.0) instructs nginx to use a list built into the OpenSSL library when using OpenSSL 1.0.2 or higher, or prime256v1 with older versions.
          ## Prior to version 1.11.0, the prime256v1 curve was used by default.
          ssl_ecdh_curve auto;
    
          ## This will create a cache shared between all worker processes.
          ## The cache size is specified in bytes (in this example: 50 MB).
          ## According to the Nginx documentation can 1MB store about 4000 sessions, so for this example, we can store about 200000 sessions, and we will store them for 180 minutes.
          ## If you expect more traffic, increase the cache size accordingly.
          ssl_session_timeout  1d;
          ssl_session_cache    shared:SSL:50m;
    
          ssl_session_tickets      off;
          # ssl_session_ticket_key /usr/local/nginx/sslkey/tls_session/tls_session_ticket.key;
    
          ssl_stapling          on;
          ssl_stapling_verify   on;
    
          ## verify chain of trust of OCSP response using Root CA and Intermediate certs.
          # ssl_trusted_certificate /path/to/signed_cert_plus_intermediates;
    
          resolver            8.8.8.8 8.8.4.4 valid=300s;
          resolver_timeout    5s;
    
          ssi                 on;
          ssi_silent_errors   off;
          ssi_types           text/shtml;
    
          location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
          {
              expires     30d;
              access_log  off;
          }
    
          location = /favicon.ico {
              rewrite (.*) /static/favicon.ico;
          }
    
          # location = /robots.txt {
          #     rewrite (.*) /static/robots.txt;
          # }
    
          location / {
              add_header Cache-Control no-cache;
    
              ## HSTS
              # add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
              add_header Strict-Transport-Security "max-age=63072000";
    
              add_header X-Frame-Options DENY;
              add_header X-Content-Type-Options nosniff;
          }
    
          # error_page 404 /static/404.html;
          access_log  /data/httplog/XXXX.com_access_ssl.log weblog;
          error_log   /data/httplog/XXXX.com_error_ssl.log;
      }
    

Nginx http配置(这里以 Nginx静态服务配置为例)

  • http.conf

      server
      {
          listen       80;
          server_name  analysis-ik.XXXX.com;
          index index.html index.htm index.php;
          root  /data/wwwroot/analysis-ik.XXXX.com/webroot;
          location = /favicon.ico {
              log_not_found off;
              access_log off;
          }
          location ~* \.(gif|jpg|jpeg|css|js|bmp|png)$ {
              expires  max;
          }
          location /status {
              stub_status on;
              access_log off;
          }
    
          location / {
              add_header Cache-Control no-cache;
          }
    
          if (-d $request_filename){
              rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
          }
          error_log  /data/httplogs/analysis-ik.XXXX.com-error.log;
          access_log  /data/httplogs/analysis-ik.XXXX.com-access.log weblog;
      }
    

参考文档

http://nginx.org/en/docs/configure.html

https://wiki.mozilla.org/Security/TLS_Configurations

https://github.com/cloudflare/sslconfig/blob/master/conf