Nginx服务之完整配置实例


纸上得来终觉浅,绝知此事要躬行。

Nginx (engine x) 是一款轻量级的 Web 服务器 、反向代理服务器及电子邮件(IMAP/POP3)代理服务器。

Nginx服务之完整配置实例

nginx -s stop       快速关闭Nginx并迅速终止web服务
nginx -s quit       平稳关闭Nginx有安排的结束web服务
nginx -s reload     因改变了Nginx相关配置需要重新加载配置而重载
nginx -s reopen     重新打开日志文件
nginx -c filename   为Nginx指定一个配置文件
nginx -t            检查配置文件语法的正确性并尝试打开配置文件中所引用到的文件
nginx -v            显示Nginx的版本
nginx -V            显示Nginx的版本/编译器版本/配置参数

完整配置实例:生产环境中使用

# 指定运行的用户
user                              nobody nobody;

# 指定启动的进程数(通常设置成和cpu的数量相等)
worker_processes                  auto;

# 指定打开的最大文件数
worker_rlimit_nofile              51200;

# 全局错误日志
error_log                         logs/error.log  notice;
error_log                         logs/notice.log  notice;
error_log                         info.log  info;

# PID文件(记录当前启动的nginx的进程ID)
pid                               /var/run/nginx.pid;

# 包含的模块配置目录路径
include                           /etc/nginx/modules-enabled/*.conf;


# 使用的模型、每个进程能够承载的请求数
events {
  use                             epoll;
  worker_connections              51200;
}

# 设定http服务器
http {
  # 是否详细显示输出信息
  server_tokens                   off;
  # 设定mime类型(邮件支持类型);类型由mime.types文件定义
  include                         mime.types;

  # 关闭重定向功能
  proxy_redirect                off;
  # 向后端服务器发送请求的主机名、IP地址、上级代理服务器(用于多级代理中)
  proxy_set_header              Host $host;
  proxy_set_header              X-Real-IP $remote_addr;
  proxy_set_header              X-Forwarded-For $proxy_add_x_forwarded_for;

  # 限制客户端的上传内容大小
  client_max_body_size          20m;
  # 设置客户端上传时的缓存内存大小,当大量用户上传时这个数值就不小了
  client_body_buffer_size       256k;
  proxy_connect_timeout         90;
  proxy_send_timeout            90;
  proxy_read_timeout            90;
  proxy_buffer_size             128k;
  proxy_buffers                 4 64k;
  proxy_busy_buffers_size       128k;
  proxy_temp_file_write_size    128k;

  default_type                    application/octet-stream;
  charset                         utf-8;

  # 设置客户端上传时缓存内存不够时,可以存放在物理磁盘上
  client_body_temp_path           /var/tmp/client_body_temp 1 2;
  proxy_temp_path                 /var/tmp/proxy_temp 1 2;
  fastcgi_temp_path               /var/tmp/fastcgi_temp 1 2;
  uwsgi_temp_path                 /var/tmp/uwsgi_temp 1 2;
  scgi_temp_path                  /var/tmp/scgi_temp 1 2;

  # 忽略无法理解的首部信息
  ignore_invalid_headers          on;
  # 对多个后端服务器名称进行哈希,提高查找效率
  server_names_hash_max_size      256;
  server_names_hash_bucket_size   64;
  client_header_buffer_size       8k;
  large_client_header_buffers     4 32k;
  connection_pool_size            256;
  request_pool_size               64k;

  output_buffers                  2 128k;
  postpone_output                 1460;

  client_header_timeout           1m;
  client_body_timeout             3m;
  send_timeout                    3m;

  # 定义日志记录格式
  log_format main                 '$server_addr $remote_addr [$time_local] $msec+$connection '
                                  '"$request" $status $connection $request_time $body_bytes_sent "$http_referer" '
                                  '"$http_user_agent" "$http_x_forwarded_for"';

  # 设置打开日志的缓存
  open_log_file_cache             max=1000 inactive=20s min_uses=1 valid=1m;
  access_log                      logs/access.log      main;
  log_not_found                   on;

  # 指定nginx是否调用sendfile函数(zero-copy)来输出文件
  # 设为on时,降低系统的uptime时间
  # 设为off时,平衡磁盘与网络I/O处理速度
  sendfile                        on;
  tcp_nodelay                     on;
  tcp_nopush                      off;

  # 连接超时时间
  reset_timedout_connection       on;
  keepalive_timeout               10 5;
  keepalive_requests              100;

  # gzip压缩开关
  gzip                            on;
  gzip_http_version               1.1;
  gzip_vary                       on;
  gzip_proxied                    any;
  gzip_min_length                 1024;
  gzip_comp_level                 6;
  gzip_buffers                    16 8k;
  gzip_proxied                    expired no-cache no-store private auth no_last_modified no_etag;
  gzip_types                      text/plain application/x-javascript text/css application/xml application/json;
  gzip_disable                    "MSIE [1-6]\.(?!.*SV1)";

  # 设定实际的服务器列表
  upstream servers {
    ip_hash;
    server                        172.16.100.103:8080 weight=1 max_fails=2;
    server                        172.16.100.104:8080 weight=1 max_fails=2;
    server                        172.16.100.105:8080 weight=1 max_fails=2;
  }

  server {
    listen                        80;
    server_name                   www.wsescape.com;

    # 编码格式
    charset utf-8;

    # 指向webapp的目录
    root                          /data/webapps/htdocs;

    # 详细的日志记录
    access_log                    /var/logs/webapp.access.log     main;
    error_log                     /var/logs/webapp.error.log      notice;

    location / {
      # 请求网站图标配置
      location ~* ^.*/favicon.ico$ {
        root                      /data/webapps;
        expires                   180d;
        break;
      }

      # 如果请求名不是一个文件,将交给后端的tomcat服务器
      if ( !-f $request_filename ) {
        proxy_pass                http://servers;
        break;
      }
    }

    # 错误处理页面(可选择性配置)
    error_page   404              /404.html;
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root                        html;
    }
  }

  server {
    listen                        8088;
    server_name                   nginx_status;

      location / {
          access_log                  off;
          deny                        all;
          return                      503;
      }

      location /status {
          stub_status                 on;
          access_log                  off;
          allow                       127.0.0.1;
          allow                       172.16.100.71;
          deny                        all;
      }
  }

  server {
      listen       443 ssl;
      server_name  www.wsescape.com;

      # ssl证书文件位置(常见证书文件格式为:crt/pem)
      ssl_certificate      cert.pem;
      # ssl证书key位置
      ssl_certificate_key  cert.key;

      # ssl配置参数(选择性配置)
      ssl_session_cache    shared:SSL:1m;
      ssl_session_timeout  5m;
      # 数字签名,此处使用MD5
      ssl_ciphers  HIGH:!aNULL:!MD5;
      ssl_prefer_server_ciphers  on;

      location / {
          root   /root;
          index  index.html index.htm;
      }
  }

}

Nginx 最佳实践 - nginx-tuning

  • [1] For Best Performance
# you must set worker processes based on your CPU cores, nginx does not benefit from setting more than that
worker_processes auto; #some last versions calculate it automatically

# number of file descriptors used for nginx
# the limit for the maximum FDs on the server is usually set by the OS.
# if you don't set FD's then OS settings will be used which is by default 2000
worker_rlimit_nofile 100000;

# only log critical errors
error_log /var/log/nginx/error.log crit;

# provides the configuration file context in which the directives that affect connection processing are specified.
events {
    # determines how much clients will be served per worker
    # max clients = worker_connections * worker_processes
    # max clients is also limited by the number of socket connections available on the system (~64k)
    worker_connections 4000;

    # optimized to serve many clients with each thread, essential for linux -- for testing environment
    use epoll;

    # accept as many connections as possible, may flood worker connections if set too low -- for testing environment
    multi_accept on;
}

http {
    # cache informations about FDs, frequently accessed files
    # can boost performance, but you need to test those values
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # to boost I/O on HDD we can disable access logs
    access_log off;

    # copies data between one FD and other from within the kernel
    # faster than read() + write()
    sendfile on;

    # send headers in one piece, it is better than sending them one by one
    tcp_nopush on;

    # reduce the data that needs to be sent over network -- for testing environment
    gzip on;
    # gzip_static on;
    gzip_min_length 10240;
    gzip_comp_level 1;
    gzip_vary on;
    gzip_disable msie6;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types
        # text/html is always compressed by HttpGzipModule
        text/css
        text/javascript
        text/xml
        text/plain
        text/x-component
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/rss+xml
        application/atom+xml
        font/truetype
        font/opentype
        application/vnd.ms-fontobject
        image/svg+xml;

    # allow the server to close connection on non responding client, this will free up memory
    reset_timedout_connection on;

    # request timed out -- default 60
    client_body_timeout 10;

    # if client stop responding, free up memory -- default 60
    send_timeout 2;

    # server will close connection after this time -- default 75
    keepalive_timeout 30;

    # number of requests client can make over keep-alive -- for testing environment
    keepalive_requests 100000;
}
  • [2] For Security Reasons
server_tokens off;
  • [3] For Simple DDoS Defense
# limit the number of connections per single IP
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;

# limit the number of requests for a given session
limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;

# zone which we want to limit by upper values, we want limit whole server
server {
    limit_conn conn_limit_per_ip 10;
    limit_req zone=req_limit_per_ip burst=10 nodelay;
}

# if the request body size is more than the buffer size, then the entire (or partial)
# request body is written into a temporary file
client_body_buffer_size  128k;

# buffer size for reading client request header -- for testing environment
client_header_buffer_size 3m;

# maximum number and size of buffers for large headers to read from client request
large_client_header_buffers 4 256k;

# read timeout for the request body from client -- for testing environment
client_body_timeout   3m;

# how long to wait for the client to send a request header -- for testing environment
client_header_timeout 3m;
  • [4] Boost Performance 9x
map $ssl_preread_protocol $upstream {
    ""        ssh.example.com:22;
    "TLSv1.2" new.example.com:443;
    default   tls.example.com:443;
}

# ssh and https on the same port
server {
    listen      192.168.0.1:443;
    proxy_pass  $upstream;
    ssl_preread on;
}

文章作者: Escape
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Escape !