`
maosheng
  • 浏览: 550077 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Nginx 配置详解

 
阅读更多
## 定义Nginx运行的用户和用户组,如果用户组省略,用户组名默认为用户名
## Syntax:user user [group];
## Default:user nobody nobody;
## Context:main

user  nginx ngnix;

## nginx进程数,建议设置为等于CPU总核心数,
## The auto parameter is supported starting from versions 1.3.8 and 1.2.5.
## Syntax:worker_processes number | auto;
## Default:worker_processes 1;
## Context:main

worker_processes  4;

## 全局错误日志定义类型,
## log level: [debug | info | notice | warn | error | crit | alert | emerg]
## Syntax:error_log file | stderr | syslog:server=address[,parameter=value]|
## memory:size [debug | info | notice | warn | error | crit | alert | emerg];
## Default:error_log logs/error.log error;
## Context:main, http, stream, server, location

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
error_log  logs/error.log  info;

## 进程文件
## Syntax:pid file;
## Default:pid nginx.pid;
## Context:main

pid        logs/nginx.pid;

## 一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数
##(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,
## 所以建议与ulimit -n的值保持一致。
## Syntax:worker_rlimit_nofile number;
## Default:—
## Context:main

worker_rlimit_nofile 65535;

## 工作模式与连接数上限
## Syntax:events { ... }
## Default:—
## Context:main

events {

    ## 参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ];   
    ## epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,
    ## 如果跑在FreeBSD上面,就用kqueue模型。
    ## Syntax:use method;
    ## Default:—
    ## Context:events  

    use epoll;

    ## 单个进程最大连接数(最大连接数=连接数*进程数)
    ## Syntax:worker_connections number;
    ## Default:worker_connections 512;
    ## Context:events

    worker_connections  20000;

}

## 设定http服务器
## Syntax:http { ... }
## Default:—
## Context:main

http {
    
     ## Includes another file, or files matching the specified mask,
     ## into configuration. Included files should consist of syntactically correct
     ## directives and blocks.
     ## Syntax: include file | mask;
     ## Default:—
     ## Context:any

     include  mime.types;

     ## 定义响应的默认MIME类型
     ## Syntax: default_type mime-type;
     ## Default:default_type text/plain;
     ## Context:http, server, location

     default_type  application/octet-stream;

     ## 指定响应头信息域Content-Type的编码格式
     ## If this charset is different from the charset specified in the
     ## source_charset directive, a conversion is performed.
     ## The parameter off cancels the addition of charset to
     ## the “Content-Type” response header field.

     ## Syntax:charset charset | off;
     ## Default:charset off;
     ## Context:http, server, location, if in location

     charset utf-8;

     ## 服务器名字的hash表大小
     ## Sets the bucket size for the server names hash tables.
     ## The default value depends on the size of the processor’s cache line

     ## Syntax: server_names_hash_bucket_size size;
     ## Default:server_names_hash_bucket_size 32|64|128;
     ## Context:http

    server_names_hash_bucket_size 128;

     ##设置读客户端请求头信息的缓存大小
     ## Sets buffer size for reading client request header. For most requests,
     ## a buffer of 1K bytes is enough. However, if a request includes long
     ## cookies, or comes from a WAP client, it may not fit into 1K.
     ## If a request line or a request header field does not fit into this buffer
     ## then larger buffers

     ## Syntax: client_header_buffer_size size;
     ## Default:client_header_buffer_size 1k;
     ## Context:http, server

    client_header_buffer_size 32k;

    ## 设置读大的客户端请求头信息的缓存的最大个数和缓存的大小
    ## Sets the maximum number and size of buffers used for reading large
    ## client request header. A request line cannot exceed the size of one buffer,
    ## or the 414 (Request-URI Too Large) error is returned to the client. A
    ## request header field cannot exceed the size of one buffer as well,
    ## or the 400 (Bad Request) error is returned to the client. Buffers are
    ## allocated only on demand. By default, the buffer size is equal to 8K bytes.
    ## If after the end of request processing a connection is transitioned into
    ## the keep-alive state, these buffers are released.

    ## Syntax: large_client_header_buffers number size;
    ## Default: large_client_header_buffers 4 8k;
    ## Context: http, server

    large_client_header_buffers 4 64k;

    ## 设置客户端请求报文体的最大允许值,设置size为0,不检查客户端请求报文体的大小
    ## Sets the maximum allowed size of the client request body, specified in the
    ## “Content-Length” request header field. If the size in a request exceeds
    ## the configured value, the 413 (Request Entity Too Large) error is returned
    ## to the client. Please be aware that browsers cannot correctly display
    ## this error.

    ## Syntax: client_max_body_size size;
    ## Default: client_max_body_size 1m;
    ## Context: http, server, location

    client_max_body_size 8m;

    ## 日志格式设定
    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  logs/access.log  main;


    ## 开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,
    ## 对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,
    ## 以平衡磁盘与网络I/O处理速度,降低系统的负载。
    ## 注意:如果图片显示不正常把这个改成off。
    ## Enables or disables the use of sendfile().

    ## Syntax:sendfile on | off;
    ## Default:sendfile off;
    ## Context:http, server, location, if in location

    sendfile  on;

    ## 开启目录列表访问,合适下载服务器,默认关闭。
    ## Enables or disables the directory listing output.

    ## Syntax:  autoindex on | off;
    ## Default: autoindex off;
    ## Context: http, server, location

    autoindex on;

    ## 防止网络阻塞,这个选项仅当sendfile开启时才生效

    ## Syntax: tcp_nopush on | off;
    ## Default: tcp_nopush off;
    ## Context: http, server, location
    ## Enables or disables the use of the TCP_NOPUSH socket option on FreeBSD or        
    ## the TCP_CORK socket option on Linux.
  
    tcp_nopush  on;


    ## 防止网络阻塞
    ## Enables or disables the use of the TCP_NODELAY option. The option is
    ## enabled only when a connection is transitioned into the keep-alive state.

    ## Syntax: tcp_nodelay on | off;
    ## Default: tcp_nodelay on;
    ## Context: http, server, location

    tcp_nodelay on;

    ## 长连接超时时间,单位是秒
    ## The first parameter sets a timeout during which a keep-alive client
    ## connection will stay open on the server side. The zero value disables
    ## keep-alive client connections. The optional second parameter sets a value
    ## in the “Keep-Alive: timeout=time” response header field.
    ## Two parameters may differ.
    ## The “Keep-Alive: timeout=time” header field is recognized by Mozilla and
    ## Konqueror. MSIE closes keep-alive connections by itself in
    ## about 60 seconds.

    ## Syntax: keepalive_timeout timeout [header_timeout];
    ## Default: keepalive_timeout 75s;
    ## Context: http, server, location

    keepalive_timeout  120;

    #gzip模块设置

    ## 开启或关闭gzip压缩输出
    ## Enables or disables gzipping of responses.

    ## Syntax: gzip on | off;
    ## Default: gzip off;
    ## Context: http, server, location, if in location

   gzip on;

    ## 最小压缩文件大小
    ## Sets the minimum length of a response that will be gzipped.
    ## The length is determined only from the “Content-Length”
    ## response header field.

    ## Syntax: gzip_min_length length;
    ## Default: gzip_min_length 20;
    ## Context: http, server, location

    gzip_min_length 1k;

    ## 压缩缓冲区个数和大小设置
    ## Sets the number and size of buffers used to compress a response.
    ## By default, the buffer size is equal to one memory page.
    ## This is either 4K or 8K, depending on a platform.

    ## Syntax: gzip_buffers number size;
    ## Default: gzip_buffers 32 4k|16 8k;
    ## Context: http, server, location

    gzip_buffers 4 16k;

    ## 压缩的HTTP版本(默认1.1,前端如果是squid2.5请使用1.0)
    ## Sets the minimum HTTP version of a request required to compress a response.

    ## Syntax: gzip_http_version 1.0 | 1.1;
    ## Default: gzip_http_version 1.1;
    ## Context: http, server, location

    gzip_http_version 1.0;

    ## 压缩等级
    ## Sets a gzip compression level of a response. Acceptable values are in
    ## the range from 1 to 9.

    ## Syntax: gzip_comp_level level;
    ## Default: gzip_comp_level 1;
    ## Context: http, server, location

    gzip_comp_level 2;

    ## 压缩类型,默认就已经包含text/html,所以下面就不用再写了,
    ## 写上去也不会有问题,但是会有一个warn。
    ## Enables gzipping of responses for the specified MIME types in addition to
    ## “text/html”. The special value “*” matches any MIME type (0.8.29).
    ## Responses with the “text/html” type are always compressed.

    ## Syntax: gzip_types mime-type ...;
    ## Default: gzip_types text/html;
    ## Context: http, server, location

    gzip_types text/plain application/x-javascript text/css application/xml;

    ## Enables or disables inserting the “Vary: Accept-Encoding”
    ## response header field if the directives gzip, gzip_static, or gunzip are active.

    ## Syntax: gzip_vary on | off;
    ## Default: gzip_vary off;
    ## Context: http, server, location

    gzip_vary on;

    ## Defines a group of servers. Servers can listen on different ports.
    ## In addition, servers listening on TCP and UNIX-domain sockets can be mixed.

    ## Example:
    ## upstream backend {
    ##     server backend1.example.com weight=5;
    ##     server 127.0.0.1:8080       max_fails=3 fail_timeout=30s;
    ##     server unix:/tmp/backend3;
    ## server backup1.example.com  backup;
    ## }
    ## By default, requests are distributed between the servers using a weighted
    ## round-robin balancing method. In the above example, each 7 requests will be
    ## distributed as follows: 5 requests go to backend1.example.com and one
    ## request to each of the second and third servers. If an error occurs during
    ## communication with a server, the request will be passed to the next server,
    ## and so on until all of the functioning servers will be tried. If a
    ## successful response could not be obtained from any of the servers, the
    ## client will receive the result of the communication with the last server.

    ## Syntax: upstream name { ... }
    ## Default: —
    ## Context: http

    upstream localhost {

         ## Defines the address and other parameters of a server. The address can
         ## be specified as a domain name or IP address, with an optional port,
         ## or as a UNIX-domain socket path specified after the “unix:” prefix.
         ## If a port is not specified, the port 80 is used. A domain name that
         ## resolves to several IP addresses defines multiple servers at once.
         ## The following parameters can be defined:
                ## weight=number
                ##     sets the weight of the server, by default, 1.
                ##     weight是权重,可以根据机器配置定义权重。
                ##     weigth参数表示权值,权值越高被分配到的几率越大
                ## max_fails=number
                ##     sets the number of unsuccessful attempts to communicate
                ##     with the server that should happen in the duration set by
                ##     the fail_timeout parameter to consider the server
                ##     unavailable for a duration also set by the fail_timeout
                ##     parameter. By default, the number of unsuccessful attempts
                ##     is set to 1. The zero value disables the accounting of
                ##     attempts. What is considered an unsuccessful attempt is
                ##     defined by the proxy_next_upstream, fastcgi_next_upstream,
                ##     uwsgi_next_upstream, scgi_next_upstream,
                ##     and memcached_next_upstream directives.
                ## fail_timeout=time
                ##     sets
                ##     the time during which the specified number of
                ##     unsuccessful attempts to communicate with the server 
                ##     should happen to consider the server unavailable;
                ##     and the period of time the server will be considered
                ##     unavailable.By default, the parameter is set to 10 seconds.
                ## backup
                ##     marks the server as a backup server. It will be passed
                ##     requests when the primary servers are unavailable.
                ## down
                ##     marks the server as permanently unavailable.
 
          ## Syntax:server address [parameters];
          ## Default:—
          ## Context:upstream
 
          server 192.168.80.121:8080 weight=3;
          server 192.168.80.122:8080 weight=2;
          server 192.168.80.123:8080 weight=3;


     }

     ## 虚拟主机的配置
     ## Sets configuration for a virtual server. There is no clear separation
     ## between IP-based (based on the IP address) and name-based
     ## (based on the “Host” request header field) virtual servers.
     ## Instead, the listen directives describe all addresses and ports that
     ## should accept connections for the server, and the server_name directive
     ## lists all server names.

     ## Syntax: server { ... }
     ## Default: —
     ## Context: http

     server {

        ## 监听端口
        ##Syntax: listen address[:port] [default_server] [ssl] [spdy]
        ##        [proxy_protocol] [setfib=number] [fastopen=number]
        ##        [backlog=number] [rcvbuf=size] [sndbuf=size]
        ##        [accept_filter=filter] [deferred] [bind] [ipv6only=on|off]
        ##        [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
        ##        listen port [default_server] [ssl] [spdy]
        ##        [proxy_protocol]
        ##        [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size]
        ##        [sndbuf=size] [accept_filter=filter] [deferred] [bind]
        ##        [ipv6only=on|off] [so_keepalive=on|off|[keepidle]:[keepintvl]:
        ##        [keepcnt]];
        ##       listen unix:path [default_server] [ssl] [spdy]
        ##        [proxy_protocol] [backlog=number] [rcvbuf=size] [sndbuf=size]
        ##        [accept_filter=filter] [deferred] [bind] [so_keepalive=on|off|
        ##        [keepidle]:[keepintvl]:[keepcnt]];
        ##Default:listen *:80 | *:8000;
        ##Context:server   

        ##Sets the address and port for IP, or the path for a UNIX-domain socket
        ##on which the server will accept requests. Both address and port, or only
        ##address or only port can be specified. 

        ##If only address is given, the port 80 is used
 
        listen   8080;

        ## Sets names of a virtual server,域名可以有多个,用空格隔开
        ## Syntax:server_name name ...;
        ## Default:server_name "";
        ## Context:server

        ##The first name becomes the primary server name.        

        server_name example.com www.example.com;

        ## Defines files that will be used as an index
        ## Syntax:index file ...;
        ## Default:index index.html;
        ## Context:http, server, location

        index index.html index.htm

        ##Sets the root directory for requests.
        ##Syntax:root path;
        ##Default:root html;
        ##Context:http, server, location, if in location

        ##For example, with the following configuration
        ##  location /i/ {
        ##         root /data/w3;
        ##  }
       
        ## The /data/w3/i/top.gif file will be sent in response to the
        ## “/i/top.gif” request.

        ## The path value can contain variables, except $document_root
        ## and $realpath_root.

        ## A path to the file is constructed by merely adding a URI to
        ## the value of the root directive.

        root /data0/htdocs

        ##Sets configuration depending on a request URI
        ##Syntax:location [ = | ~ | ~* | ^~ ] uri { ... }
        ##       location @name { ... }
        ##Default: —
        ##Context:server, location

        ##A location can either be defined by a prefix string, or by a regular
        ##expression. Regular expressions are specified with the preceding “~*”
        ##modifier (for case-insensitive matching), or the “~” modifier (for
        ##case-sensitive matching). To find location matching a given request,     
        ##nginx first checks locations defined using the prefix strings (prefix
        ##locations). Among them, the location with the longest matching prefix is
        ##selected and remembered. Then regular expressions are checked, in the
        ##order of their appearance in the configuration file. The search of
        ##regular expressions terminates on the first match, and the corresponding
        ##configuration is used. If no match with a regular expression is found
        ##then the configuration of the prefix location remembered earlier
        ##is used.
        ##Let’s illustrate the above by an example:

        ## location = / {
        ##     [ configuration A ]
        ## }

        ## location / {
        ##     [ configuration B ]
        ## }

        ## location /documents/ {
        ##     [ configuration C ]
        ## }

        ## location ^~ /images/ {
        ##     [ configuration D ]
        ## }

        ## location ~* \.(gif|jpg|jpeg)$ {
        ##     [ configuration E ]
        ## }

        ## The “/” request will match configuration A, the “/index.html”
        ## request will match configuration B, the “/documents/document.html”
        ## request will match configuration C, the “/images/1.gif” request will
        ## match configuration D, and the “/documents/1.jpg” request will
        ## match configuration E.

        ## 对 "/" 启用反向代理
        location / {
                    ##后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
                    proxy_set_header X-Real-IP $remote_addr;
                    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

                    ##以下是一些反向代理的配置,可选。
                    proxy_set_header Host $host:8080;

                    proxy_redirect off;

                    ##允许客户端请求的最大单文件字节数
                    client_max_body_size 10m;

                    ##缓冲区代理缓冲用户端请求的最大字节数
                    client_body_buffer_size 128k;

                    ##nginx跟后端服务器连接超时时间(代理连接超时)
                    proxy_connect_timeout 90;

                    ##后端服务器数据回传时间(代理发送超时)
                    proxy_send_timeout 90;

                    ##连接成功后,后端服务器响应时间(代理接收超时)
                    proxy_read_timeout 90;

                    ##设置代理服务器(nginx)保存用户头信息的缓冲区大小
                    proxy_buffer_size 4k;

                    ##proxy_buffers缓冲区,网页平均在32k以下的设置
                    proxy_buffers 4 32k;

                    ##高负荷下缓冲大小(proxy_buffers*2)
                    proxy_busy_buffers_size 64k;

                    ##设定缓存文件夹大小,大于这个值,将从upstream服务器传
                    proxy_temp_file_write_size 64k;

                    ## Sets the address of a proxied server
                    ## Syntax: proxy_pass address;
                    ## Default: —
                    ## Context: server
                    proxy_pass http://localhost;


        }

        ##本地动静分离反向代理配置
        ##所有jsp的页面均交由tomcat或glassfish处理

        location ~ .(jsp|jspx|do)?$ {
               proxy_set_header Host $host;
               proxy_set_header X-Real-IP $remote_addr;
               proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
               proxy_pass http://127.0.0.1:8080;
        }

        ##所有静态文件由nginx直接读取不经过tomcat或glassfish
        ##图片缓存时间设置

        location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
        {
            expires 15d;
        }

        ##JS和CSS缓存时间设置
        location ~ .*.(js|css)?$
        {
            expires 1h;
        }

        ##Syntax:error_page code ... [=[response]] uri;
        ##Default:—
        ##Context:http, server, location, if in location
        ## Defines the URI that will be shown for the specified errors. error_page
        ## directives are inherited from the previous level only if there are no
        ## error_page directives defined on the current level. A uri value can
        ## contain variables.

        ## Example:

        ##    error_page 404             /404.html;
        ##    error_page 500 502 503 504 /50x.html;

        ## Furthermore, it is possible to change the response code to another
        ## using the “=response” syntax, for example:

        ## error_page 404 =200 /empty.gif;

        #error_page  404   /404.html;
        error_page   500 502 503 504  /50x.html;

        ##redirect server error pages to the static page /50x.html

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

        ##设定查看Nginx状态的地址
        location /NginxStatus {
            stub_status on;
            access_log on;
            auth_basic "NginxStatus";
            auth_basic_user_file conf/htpasswd;
            #htpasswd文件的内容可以用apache提供的htpasswd工具来产生。
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

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


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

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


更详细的模块参数请参考: http://nginx.org/en/docs/dirindex.html

配置完成后,检查一下nginx配置文件是否可用,有successful表示可用。 

$ nginx -t // 检查nginx配置文件 

配置正确后,重新加载配置文件使配置生效: 

$ nginx -s reload // 使配置生效


nginx配置https访问


server {
    listen 443;
    server_name bjubi.com; // 你的域名
    client_max_body_size  30m;

    ssl on;
    ssl_certificate  cert/214292799730473.crt;// 改成你的证书的名字
    ssl_certificate_key cert/214292799730473.key;// 你的证书的名字
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 sslv3;
    ssl_prefer_server_ciphers on;

    location / {

            proxy_pass  http://120.22.85.211:8080;
            proxy_set_header    X-Real-IP  $remote_addr;
            proxy_set_header    Host       $host;
            proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
            proxy_buffer_size 4k;
            proxy_buffers 4 32k;
            proxy_busy_buffers_size 64k;
            proxy_temp_file_write_size 64k;
            proxy_max_temp_file_size 512m;

    }
}
server {

    listen 80;
    server_name bjubi.com;// 你的域名
    rewrite ^(.*)$ https://$host$1 permanent;// 把http的域名请求转成https

}






分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics