Nginx HTTP 配置示例

Nginx HTTP 配置示例

Nginx HTTP configuration

Full Example Configuration

Example configurations from official wiki1.

nginx.conf

user        www www;  ## Default: nobody
worker_processes  5;  ## Default: 1
error_log  logs/error.log;
pid        logs/nginx.pid;
worker_rlimit_nofile 8192;

events {
  worker_connections  4096;  ## Default: 1024
}

http {
  include    conf/mime.types;
  include    /etc/nginx/proxy.conf;
  include    /etc/nginx/fastcgi.conf;
  index      index.html index.htm index.php;

  default_type application/octet-stream;
  log_format   main '$remote_addr - $remote_user [$time_local]  $status '
    '"$request" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';
  access_log   logs/access.log  main;
  sendfile     on;
  tcp_nopush   on;
  server_names_hash_bucket_size 128; # this seems to be required for some vhosts

  server { # php/fastcgi
    listen       80;
    server_name  domain1.com www.domain1.com;
    access_log   logs/domain1.access.log  main;
    root         html;

    location ~ \.php$ {
      fastcgi_pass 127.0.0.1:1025;
    }
  }

  server { # simple reverse-proxy
    listen       80;
    server_name  domain2.com www.domain2.com;
    access_log   logs/domain2.access.log  main;

    # serve static files
    location ~ ^/(images|javascript|js|css|flash|media|static)/  {
      root    /var/www/virtual/big.server.com/htdocs;
      expires 30d;
    }

    # pass requests for dynamic content to rails/turbogears/zope, et al
    location / {
      proxy_pass http://127.0.0.1:8080;
    }
  }

  upstream big_server_com {
    server 127.0.0.3:8000 weight=5;
    server 127.0.0.3:8001 weight=5;
    server 192.168.0.1:8000;
    server 192.168.0.1:8001;
  }

  server { # simple load balancing
    listen          80;
    server_name     big.server.com;
    access_log      logs/big.server.access.log main;

    location / {
      proxy_pass    http://big_server_com;
    }
  }
}

proxy.conf

proxy_redirect          off;
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    10m;
client_body_buffer_size 128k;
proxy_connect_timeout   90;
proxy_send_timeout      90;
proxy_read_timeout      90;
proxy_buffers           32 4k;

fastcgi.conf

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;
fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

fastcgi_index  index.php;

fastcgi_param  REDIRECT_STATUS    200;

mime.types

types {
  text/html                             html htm shtml;
  text/css                              css;
  text/xml                              xml rss;
  image/gif                             gif;
  image/jpeg                            jpeg jpg;
  application/x-javascript              js;
  text/plain                            txt;
  text/x-component                      htc;
  text/mathml                           mml;
  image/png                             png;
  image/x-icon                          ico;
  image/x-jng                           jng;
  image/vnd.wap.wbmp                    wbmp;
  application/java-archive              jar war ear;
  application/mac-binhex40              hqx;
  application/pdf                       pdf;
  application/x-cocoa                   cco;
  application/x-java-archive-diff       jardiff;
  application/x-java-jnlp-file          jnlp;
  application/x-makeself                run;
  application/x-perl                    pl pm;
  application/x-pilot                   prc pdb;
  application/x-rar-compressed          rar;
  application/x-redhat-package-manager  rpm;
  application/x-sea                     sea;
  application/x-shockwave-flash         swf;
  application/x-stuffit                 sit;
  application/x-tcl                     tcl tk;
  application/x-x509-ca-cert            der pem crt;
  application/x-xpinstall               xpi;
  application/zip                       zip;
  application/octet-stream              deb;
  application/octet-stream              bin exe dll;
  application/octet-stream              dmg;
  application/octet-stream              eot;
  application/octet-stream              iso img;
  application/octet-stream              msi msp msm;
  audio/mpeg                            mp3;
  audio/x-realaudio                     ra;
  video/mpeg                            mpeg mpg;
  video/quicktime                       mov;
  video/x-flv                           flv;
  video/x-msvideo                       avi;
  video/x-ms-wmv                        wmv;
  video/x-ms-asf                        asx asf;
  video/x-mng                           mng;
}

HTTP 核心配置示例

Nginx 最核心的功能就是处理 HTTP 请求。HTTP 请求处理的简单闭环流程模型是当客户端发起 HTTP 请求后,服务端会解析 HTTP 请求头,并根据请求头中访问的 URI 与本地路径文件进行匹配,进行读取数据或写数据的操作,然后返回处理结果并断开 HTTP 连接。当然,Nginx 内部处理过程更加复杂,结合 HTTP 请求处理闭环流程模型和 Nginx 的 HTTP 核心配置指令,可以分为如下几类2

  • 初始化服务
  • HTTP 请求解析
  • 访问路由 location
  • 访问重写 rewrite
  • 访问控制
  • 数据处理
  • 关闭连接
  • 日志记录
http {
    resolver 192.168.2.53 valid=30s; # 全局域名解析服务器为 192.168.2.53,并设置 30s 更新一次 DNS 缓存
    resolver_timeout 10s;            # 域名解析超时时间为 10s

    variables_hash_max_size 1024;  # Nginx 变量的 hash 表的大小为 1024 字节
    variables_hash_bucket_size 64; # Nginx 变量的 hash 表的哈希桶的大小是 64 字节

    types_hash_max_size 1024;  # MIME 类型映射表哈希表的大小为 1024 字节
    types_hash_bucket_size 64; # MIME 类型映射表哈希桶的大小是 64 字节

    # 请求解析,HTTP 全局有效
    ignore_invalid_headers on;         # 忽略请求头中无效的属性名
    underscores_in_headers on;         # 允许请求头的属性名中有下划线 "_"
    client_header_buffer_size 2k;      # 客户请求头缓冲区大小为 2KB
    large_client_header_buffers 4 16k; # 超大客户请求头缓冲区大小为 64KB
    client_header_timeout 30s;         # 读取客户请求头的超时时间是 30s
    request_pool_size 4k;              # 请求池的大小是 4K

    merge_slashes on;  # 当 URI 中有连续的斜线时做合并处理
    server_tokens off; # 当返回错误信息时,不显示 Nginx 的版本号信息
    msie_padding on;   # 当客户端请求出错时,在响应数据中添加注释

    subrequest_output_buffer_size 8k; # 子请求响应报文缓冲区大小为 8KB

    lingering_close on;           # Nginx 主动关闭连接时启用延迟关闭
    lingering_time 60s;           # 延迟关闭处理数据的最长时间是 60s
    lingering_timeout 5s;         # 延迟关闭的超时时间是 5s
    reset_timedout_connection on; # 当 Nginx 主动关闭连接而客户端无响应时,在连接超时后进行关闭

    log_not_found on;  # 将未找到文件的错误信息记录到日志中
    log_subrequest on; # 将子请求的访问日志记录到访问日志中

    error_page 404 /404.html;             # 所有请求的 404 状态码返回 404.html 文件的数据
    error_page 500 502 503 504 /50x.html; # 所有请求的 500、502、503、504 状态码返回 50x.html 文件的数据

    server {
        # 监听本机的 8000 端口,当前服务是 http 指令域的主服务,开启 fastopen 功能并限定最大队列数是 30,拒绝空数据连接,Nginx 工作进程共享 socket 监听端口,当请求阻塞时挂起队列数是 1024
        listen *:8000 default_server fastopen=30 deferred reuseport backlog=1024 so_keepalive=on;

        server_name a.nginxbar.com b.nginxtest.com c.nginxbar.com;
        server_names_hash_max_size 1024;   # 服务主机名哈希桶大小为 128 字节
        server_names_hash_bucket_size 128; # 服务主机名哈希桶大小为 128 字节

        # 保持连接配置
        keepalive_disable msie6; # 对 MSIE6 版本的客户端关闭保持连接机制
        keepalive_requests 1000; # 保持连接可复用的 HTTP 连接为 1000 个
        keepalive_timeout 60s;   # 保持连接空置超时时间为 60s
        tcp_nodelay on;          # 当处于保持连接状态时,以最快的方式发送数据包

        # 本地文件相关配置
        root /var/www/html;   # 当前服务对应本地文件访问的根目录时 /var/www/html
        disable_symlinks off; # 对本地文件路径中的符号链接不做检测

        # 静态文件场景
        location / {
            server_name_in_redirect on; # 在重定向时,拼接服务主机名
            port_in_redirect on;        # 在重定向时,拼接服务主机端口

            if_modified_since exact;    # 当请求头中有 if_modified_since 属性时,与被请求的本地文件修改时间做精确匹配处理
            etag on;         # 启用 etag 功能
            msie_refresh on; # 当客户端是 MSIE 时,以添加 HTML 头信息的方式执行跳转

            open_file_cache max=1000 inactive=20s; # 对被打开文件启用缓存支持,缓存元素数最大为 1000 个,不活跃的缓存元素保存 20s
            open_file_cache_errors on;  # 对无法找到文件的错误元素也进行缓存
            open_file_cache_min_uses 2; # 缓存中的元素至少要被访问两次才为活跃
            open_file_cache_valid 60s;  # 每 60s 对缓存元素与本地文件进行一次检查
        }

        # 上传场景
        location /upload {
            alias /data/upload;      # 将 upload 的请求重定位到目录 /data/upload
            limit_except GET {       # 对除 GET 意外的方法进行限制
                allow 192.168.100.1; # 允许 192.168.100.1 执行所有请求方法
                deny all;            # 其他 IP 只允许执行 GET 方法
            }
            client_max_body_size 200m;             # 允许上传的最大文件大小是 200MB
            client_body_buffer_size 16k;           # 上传缓冲区的大小是 16KB
            client_body_in_file_only off;          # 不禁用上传缓冲区
            client_body_temp_path /tmp/upload 1 2; # 设置请求体临时文件存储目录
            client_body_timeout 120s;              # 请求体接收超时时间为 120s
        }

        # 下载场景
        location /download {
            alias /data/download; # 将 download 的请求重定位到目录 /data/download
            types {}
            default_type application/octet-stream; # 设置当前目录所有文件默认 MIME 类型为 application/octet-stream

            try_files $uri @nofile; # 当文件不存在时,跳转到 location @nofile
            sendfile on;            # 开启零复制文件传输功能
            sendfile_max_chunk 1M;  # 每个 sendfile 调用的最大传输量为 1MB
            tcp_nopush on;          # 启用最小传输限制功能

            aio on;                  # 启用异步传输
            directio 5M;             # 当文件大于 5MB 时以直接读取磁盘方式读取文件
            directio_alignment 4096; # 与磁盘的文件系统对齐
            output_buffers 4 32k;    # 文件输出的缓冲区为 128KB (4*32)

            limit_rate 1m;                # 限制下载速度为 1MB
            limit_rate_after 2m;          # 当客户端下载速度达到 2MB 时,进入限速模式
            max_ranges 4096;              # 客户端执行范围读取的最大值是 4096B
            send_timeout 20s;             # 客户端引发传输超时时间为 20s
            postpone_output 2048        # 当缓冲区的数据达到 2048B 时再向客户端发送
            chunked_transfer_encoding on; # 启用分块传输标识
        }

        location @nofile {
            index nofile.html
        }
        
        location = /404.html {
            internal;
        }

        location = /50x.html {
            internal;
        }
    }
}

以上仅用作示例……

  1. Full Example Configuration

  2. Nginx 应用与运维实战。 

THE END
Ads by Google

林宏

Frank Lin

Hey, there! This is Frank Lin (@flinhong), one of the 1.41 billion . This 'inDev. Journal' site holds the exploration of my quirky thoughts and random adventures through life. Hope you enjoy reading and perusing my posts.

YOU MAY ALSO LIKE

HTML 相对路径和绝对路径区别分析

Web Notes

2015.09.26

HTML 相对路径和绝对路径区别分析

HTML 初学者会经常遇到这样一个问题,如何正确引用一个文件。比如,怎样在一个 HTML 网页中引用另外一个 HTML 网页作为超链接(hyperlink),怎样在一个网页中插入一张图片。如果你在引用文件时(如加入超链接,或者插入图片等),使用了错误的文件路径,就会导致引用失效(无法浏览链接文件,或无法显示插入的图片等)。

Understanding Nginx location directive

Tools

2020.09.12

Understanding Nginx location directive

Location directives are essential when working with Nginx. They can be located within server blocks or other location blocks. Understanding how location directives are used to process the URI of client request can help make the request handling less unpredictable.

TOC

Ads by Google