Nginx记录-Nginx基础(转载)

1.Nginx经常使用功能

一、Http代理,反向代理:做为web服务器最经常使用的功能之一,尤为是反向代理。javascript

Nginx在作反向代理时,提供性能稳定,而且可以提供配置灵活的转发功能。Nginx能够根据不一样的正则匹配,采起不一样的转发策略,好比图片文件结尾的走文件服务器,动态页面走web服务器,只要你正则写的没问题,又有相对应的服务器解决方案,你就能够为所欲为的玩。而且Nginx对返回结果进行错误页跳转,异常判断等。若是被分发的服务器存在异常,他能够将请求从新转发给另一台服务器,而后自动去除异常服务器。php

二、负载均衡css

Nginx提供的负载均衡策略有2种:内置策略和扩展策略。内置策略为轮询,加权轮询,Ip hash。扩展策略,就天马行空,只有你想不到的没有他作不到的啦,你能够参照全部的负载均衡算法,给他一一找出来作下实现。html

上3个图,理解这三种负载均衡算法的实现java

Ip hash算法,对客户端请求的ip进行hash操做,而后根据hash结果将同一个客户端ip的请求分发给同一台服务器进行处理,能够解决session不共享的问题。 node

三、web缓存linux

Nginx能够对不一样的文件作不一样的缓存处理,配置灵活,而且支持FastCGI_Cache,主要用于对FastCGI的动态程序进行缓存。配合着第三方的ngx_cache_purge,对制定的URL缓存内容能够的进行增删管理。nginx

2.Nginx文件配置

1.默认的configweb

#user  nobody;
worker_processes  1;

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

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #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        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

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

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # 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;
    #    }
    #}

}

2.nginx文件结构算法

main                                # 全局配置

events {                            # nginx工做模式配置

}

http {                                # http设置
    ....

    server {                        # 服务器主机配置
        ....
        location {                    # 路由配置
            ....
        }

        location path {
            ....
        }

        location otherpath {
            ....
        }
    }

    server {
        ....

        location {
            ....
        }
    }

    upstream name {                    # 负载均衡配置
        ....
    }
}

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

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

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

4)server块:配置虚拟主机的相关参数,一个http中能够有多个server。

5)location块:配置请求的路由,以及各类页面的处理状况。

6)upstream:用于进行负载均衡的配置

3.main块

# user nobody nobody;
worker_processes 2;
# error_log logs/error.log
# error_log logs/error.log notice
# error_log logs/error.log info
# pid logs/nginx.pid
worker_rlimit_nofile 1024;

上述配置都是存放在main全局配置模块中的配置项

  • user用来指定nginx worker进程运行用户以及用户组,默认nobody帐号运行
  • worker_processes指定nginx要开启的子进程数量,运行过程当中监控每一个进程消耗内存(通常几M~几十M不等)根据实际状况进行调整,一般数量是CPU内核数量的整数倍
  • error_log定义错误日志文件的位置及输出级别【debug / info / notice / warn / error / crit】
  • pid用来指定进程id的存储文件的位置
  • worker_rlimit_nofile用于指定一个进程能够打开最多文件数量的描述

4.event 模块

event {
    worker_connections 1024;
    multi_accept on;
    use epoll;
}

上述配置是针对nginx服务器的工做模式的一些操做配置

  • worker_connections 指定最大能够同时接收的链接数量,这里必定要注意,最大链接数量是和worker processes共同决定的。
  • multi_accept 配置指定nginx在收到一个新链接通知后尽量多的接受更多的链接
  • use epoll 配置指定了线程轮询的方法,若是是linux2.6+,使用epoll,若是是BSD如Mac请使用Kqueue

5.http模块

做为web服务器,http模块是nginx最核心的一个模块,配置项也是比较多的,项目中会设置到不少的实际业务场景,须要根据硬件信息进行适当的配置,常规状况下,使用默认配置便可!

http {
    ##
    # 基础配置
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL证书配置
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # 日志配置
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip 压缩配置
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript
 text/xml application/xml application/xml+rss text/javascript;

    ##
    # 虚拟主机配置
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

1) 基础配置

sendfile on:配置on让sendfile发挥做用,将文件的回写过程交给数据缓冲去去完成,而不是放在应用中完成,这样的话在性能提高有有好处
tc_nopush on:让nginx在一个数据包中发送全部的头文件,而不是一个一个单独发
tcp_nodelay on:让nginx不要缓存数据,而是一段一段发送,若是数据的传输有实时性的要求的话能够配置它,发送完一小段数据就马上能获得返回值,可是不要滥用哦

keepalive_timeout 10:给客户端分配链接超时时间,服务器会在这个时间事后关闭链接。通常设置时间较短,可让nginx工做持续性更好
client_header_timeout 10:设置请求头的超时时间
client_body_timeout 10:设置请求体的超时时间
send_timeout 10:指定客户端响应超时时间,若是客户端两次操做间隔超过这个时间,服务器就会关闭这个连接

limit_conn_zone $binary_remote_addr zone=addr:5m :设置用于保存各类key的共享内存的参数,
limit_conn addr 100: 给定的key设置最大链接数

server_tokens:虽然不会让nginx执行速度更快,可是能够在错误页面关闭nginx版本提示,对于网站安全性的提高有好处哦
include /etc/nginx/mime.types:指定在当前文件中包含另外一个文件的指令
default_type application/octet-stream:指定默认处理的文件类型能够是二进制
type_hash_max_size 2048:混淆数据,影响三列冲突率,值越大消耗内存越多,散列key冲突率会下降,检索速度更快;值越小key,占用内存较少,冲突率越高,检索速度变慢

2) 日志配置

access_log logs/access.log:设置存储访问记录的日志
error_log logs/error.log:设置存储记录错误发生的日志

3) SSL证书加密

ssl_protocols:指令用于启动特定的加密协议,nginx在1.1.13和1.0.12版本后默认是ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2,TLSv1.1与TLSv1.2要确保OpenSSL >= 1.0.1 ,SSLv3 如今还有不少地方在用但有很多被攻击的漏洞。
ssl prefer server ciphers:设置协商加密算法时,优先使用咱们服务端的加密套件,而不是客户端浏览器的加密套件

4) 压缩配置

gzip 是告诉nginx采用gzip压缩的形式发送数据。这将会减小咱们发送的数据量。
gzip_disable 为指定的客户端禁用gzip功能。咱们设置成IE6或者更低版本以使咱们的方案可以普遍兼容。
gzip_static 告诉nginx在压缩资源以前,先查找是否有预先gzip处理过的资源。这要求你预先压缩你的文件(在这个例子中被注释掉了),从而容许你使用最高压缩比,这样nginx就不用再压缩这些文件了(想要更详尽的gzip_static的信息,请点击这里)。
gzip_proxied 容许或者禁止压缩基于请求和响应的响应流。咱们设置为any,意味着将会压缩全部的请求。
gzip_min_length 设置对数据启用压缩的最少字节数。若是一个请求小于1000字节,咱们最好不要压缩它,由于压缩这些小的数据会下降处理此请求的全部进程的速度。
gzip_comp_level 设置数据的压缩等级。这个等级能够是1-9之间的任意数值,9是最慢可是压缩比最大的。咱们设置为4,这是一个比较折中的设置。
gzip_type 设置须要压缩的数据格式。上面例子中已经有一些了,你也能够再添加更多的格式。

5) 文件缓存配置

open_file_cache 打开缓存的同时也指定了缓存最大数目,以及缓存的时间。咱们能够设置一个相对高的最大时间,这样咱们能够在它们不活动超过20秒后清除掉。
open_file_cache_valid 在open_file_cache中指定检测正确信息的间隔时间。
open_file_cache_min_uses 定义了open_file_cache中指令参数不活动时间期间里最小的文件数。
open_file_cache_errors 指定了当搜索一个文件时是否缓存错误信息,也包括再次给配置中添加文件。咱们也包括了服务器模块,这些是在不一样文件中定义的。若是你的服务器模块不在这些位置,你就得修改这一行来指定正确的位置。

6.server模块

srever模块配置是http模块中的一个子模块,用来定义一个虚拟访问主机,也就是一个虚拟服务器的配置信息

server {
    listen        80;
    server_name localhost    192.168.1.100;
    root        /nginx/www;
    index        index.php index.html index.html;
    charset        utf-8;
    access_log    logs/access.log;
    error_log    logs/error.log;
    ......
}

核心配置信息以下:

  • server:一个虚拟主机的配置,一个http中能够配置多个server

  • server_name:用力啊指定ip地址或者域名,多个配置之间用空格分隔

  • root:表示整个server虚拟主机内的根目录,全部当前主机中web项目的根目录

  • index:用户访问web网站时的全局首页

  • charset:用于设置www/路径中配置的网页的默认编码格式

  • access_log:用于指定该虚拟主机服务器中的访问记录日志存放路径

  • error_log:用于指定该虚拟主机服务器中访问错误日志的存放路径

7.location块

location模块是nginx配置中出现最多的一个配置,主要用于配置路由访问信息

在路由访问信息配置中关联到反向代理、负载均衡等等各项功能,因此location模块也是一个很是重要的配置模块

基本配置

location / {
    root    /nginx/www;
    index    index.php index.html index.htm;
}

location /:表示匹配访问根目录

root:用于指定访问根目录时,访问虚拟主机的web目录

index:在不指定访问具体资源时,默认展现的资源文件列表

反向代理配置方式

经过反向代理代理服务器访问模式,经过proxy_set配置让客户端访问透明化

location / {
    proxy_pass http://localhost:8888;
    proxy_set_header X-real-ip $remote_addr;
    proxy_set_header Host $http_host;
}

uwsgi配置

wsgi模式下的服务器配置访问方式

location / {
    include uwsgi_params;
    uwsgi_pass localhost:8888
}

8.upstream模块

upstream模块主要负责负载均衡的配置,经过默认的轮询调度方式来分发请求到后端服务器

简单的配置方式以下

 

  upstream test {
            server 192.168.0.1 weight=5;
            ip_hash;
            server 192.168.0.2 weight=7;
        }

 

upstream name {
    ip_hash;
    server 192.168.1.100:8000;
    server 192.168.1.100:8001 down;
    server 192.168.1.100:8002 max_fails=3;
    server 192.168.1.100:8003 fail_timeout=20s;
    server 192.168.1.100:8004 max_fails=3 fail_timeout=20s;
}

核心配置信息以下

  • ip_hash:指定请求调度算法,默认是weight权重轮询调度,能够指定

  • server host:port:分发服务器的列表配置

  • -- down:表示该主机暂停服务

  • -- max_fails:表示失败最大次数,超过失败最大次数暂停服务

  • -- fail_timeout:表示若是请求受理失败,暂停指定的时间以后从新发起请求

9.nginx配置例子

########### 每一个指令必须有分号结束。#################
#user administrator administrators;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #容许生成的进程数,默认为1
#pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址
error_log log/error.log debug;  #制定日志路径,级别。这个设置能够放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {
    accept_mutex on;   #设置网路链接序列化,防止惊群现象发生,默认为on
    multi_accept on;  #设置一个进程是否同时接受多个网络链接,默认为off
    #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大链接数,默认为512
}
http {
    include       mime.types;   #文件扩展名与文件类型映射表
    default_type  application/octet-stream; #默认文件类型,默认为text/plain
    #access_log off; #取消服务日志    
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
    access_log log/access.log myFormat;  #combined为日志格式的默认值
    sendfile on;   #容许sendfile方式传输文件,默认为off,能够在http块,server块,location块。
    sendfile_max_chunk 100k;  #每一个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
    keepalive_timeout 65;  #链接超时时间,默认为75s,能够在http,server,location块。

    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #热备
    }
    error_page 404 https://www.baidu.com; #错误页
    server {
        keepalive_requests 120; #单链接请求上限次数。
        listen       4545;   #监听端口
        server_name  127.0.0.1;   #监听地址       
        location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
           #root path;  #根目录
           #index vv.txt;  #设置默认页
           proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
           deny 127.0.0.1;  #拒绝的ip
           allow 172.18.5.54; #容许的ip           
        } 
    }
} 

3.nginx部署

##安装nginx
yum -y install nginx

## 查看 Nginx 程序文件目录:/usr/sbin/nginx
$ ps  -ef | grep nginx

## 查看 nginx.conf 配置文件目录:/etc/nginx/nginx.conf
$ nginx -t                 
$ vim /etc/nginx/nginx.conf

## 配置文件目录:/etc/nginx

## 虚拟主机配置文件目录:/etc/nginx/sites-available/
## 虚拟主机文件夹目录:/var/www/,详情可在 /etc/nginx/sites-available/ 中配置
## 默认网页文件目录:/usr/share/nginx/html

## 测试配置文件,只检查配置文件是否存在语法错误
$ nginx -t -c <path-to-nginx.conf>
$ sudo nginx -t -c /etc/nginx/nginx.conf

## 启动 Nginx 服务
$ nginx 安装目录 -c <path-to-nginx.conf>
$ sudo /etc/init.d/nginx start

## 中止 Nginx 服务
$ sudo /usr/sbin/nginx -s stop 

## 重启 Nginx 
$ sudo /usr/sbin/nginx -s reload  # 0.8 版本以后的方法
$ kill -HUP pid     # 向 master 进程发送信号从容地重启 Nginx,即服务不中断

$ sudo service nginx start
$ sudo service nginx stop
$ sudo service nginx restart
Nginx 配置文件路径:/etc/nginx/nginx.conf
##
# 全局配置
##

user www-data;             ## 配置 worker 进程的用户和组
worker_processes auto;     ## 配置 worker 进程启动的数量,建议配置为 CPU 核心数
error_log logs/error.log;  ## 全局错误日志
pid /run/nginx.pid;        ## 设置记录主进程 ID 的文件
worker_rlimit_nofile 8192; ## 配置一个工做进程可以接受并发链接的最大数

##
# 工做模式及链接数上限
##
events {
    # epoll 是多路复用 IO(I/O Multiplexing)中的一种方式,
    # 仅用于 Linux 2.6 以上内核,能够大大提升 Nginx 性能
    use epoll
        
    # 单个后台 worker process 进程的最大并发连接数
    # 并发总数 max_clients = worker_professes * worker_connections
    worker_connections 4096;  ## Defaule: 1024
    # multi_accept on;  ## 指明 worker 进程马上接受新的链接
}

##
# http 模块
##

http {

    ##
    # Basic Settings
    ##
    
    #sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,
    #对于普通应用,必须设为 on,
    #若是用来进行下载等应用磁盘 IO 重负载应用,可设置为 off,
    #以平衡磁盘与网络 I/O 处理速度,下降系统的 uptime.
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;      ## 链接超时时间
    types_hash_max_size 2048;  ## 指定散列类型表的最大大小
    # server_tokens off;

    # server_names_hash_bucket_size 64;  # this seems to be required for some vhosts
    # server_name_in_redirect off;
    
    include /etc/nginx/mime.types;  ## 设定 mine 类型
    default_type application/octet-stream;
   
    # 设定请求缓冲
    client_header_buffer_size    128k; # 指定客户端请求头缓存大小,当请求头大于 1KB 时会用到该项
    large_client_header_buffers  4 128k; # 最大数量和最大客户端请求头的大小
    
    ##
    # SSL Settings
    ##
    
    # 启用全部协议,禁用已废弃的不安全的SSL 2 和SSL 3
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    # 让服务器选择要使用的算法套件
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;  ## 访问日志
    error_log /var/log/nginx/error.log;    ## 错误日志

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;   # 这个文件夹默认是空的
    include /etc/nginx/sites-enabled/*; # 开启的 Server 服务配置

}

##
# mail 模块
##
        
mail {
    # See sample authentication script at:
    # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript

    # auth_http localhost/auth.php;
    # pop3_capabilities "TOP" "USER";
    # imap_capabilities "IMAP4rev1" "UIDPLUS";

    server {
        listen     localhost:110;
        protocol   pop3;
        proxy      on;
    }

    server {
        listen     localhost:143;
        protocol   imap;
        proxy      on;
    }
}
nginx web配置例子
#运行用户
user nobody;
#启动进程,一般设置成和cpu的数量相等
worker_processes  1;

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

#pid        logs/nginx.pid;

#工做模式及链接数上限
events {
    #epoll是多路复用IO(I/O Multiplexing)中的一种方式,
    #仅用于linux2.6以上内核,能够大大提升nginx的性能
    use   epoll; 

    #单个后台worker process进程的最大并发连接数    
    worker_connections  1024;

    # 并发总数是 worker_processes 和 worker_connections 的乘积
    # 即 max_clients = worker_processes * worker_connections
    # 在设置了反向代理的状况下,max_clients = worker_processes * worker_connections / 4  为何
    # 为何上面反向代理要除以4,应该说是一个经验值
    # 根据以上条件,正常状况下的Nginx Server能够应付的最大链接数为:4 * 8000 = 32000
    # worker_connections 值的设置跟物理内存大小有关
    # 由于并发受IO约束,max_clients的值须小于系统能够打开的最大文件数
    # 而系统能够打开的最大文件数和内存大小成正比,通常1GB内存的机器上能够打开的文件数大约是10万左右
    # 咱们来看看360M内存的VPS能够打开的文件句柄数是多少:
    # $ cat /proc/sys/fs/file-max
    # 输出 34336
    # 32000 < 34336,即并发链接总数小于系统能够打开的文件句柄总数,这样就在操做系统能够承受的范围以内
    # 因此,worker_connections 的值需根据 worker_processes 进程数目和系统能够打开的最大文件总数进行适当地进行设置
    # 使得并发总数小于操做系统能够打开的最大文件数目
    # 其实质也就是根据主机的物理CPU和内存进行配置
    # 固然,理论上的并发总数可能会和实际有所误差,由于主机还有其余的工做进程须要消耗系统资源。
    # ulimit -SHn 65535

}


http {
    #设定mime类型,类型由mime.type文件定义
    include    mime.types;
    default_type  application/octet-stream;
    #设定日志格式
    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 函数(zero copy 方式)来输出文件,
    #对于普通应用,必须设为 on,
    #若是用来进行下载等应用磁盘IO重负载应用,可设置为 off,
    #以平衡磁盘与网络I/O处理速度,下降系统的uptime.
    sendfile     on;
    #tcp_nopush     on;

    #链接超时时间
    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay     on;

    #开启gzip压缩
    gzip  on;
    gzip_disable "MSIE [1-6].";

    #设定请求缓冲
    client_header_buffer_size    128k;
    large_client_header_buffers  4 128k;


    #设定虚拟主机配置
    server {
        #侦听80端口
        listen    80;
        #定义使用 www.nginx.cn访问
        server_name  www.nginx.cn;

        #定义服务器的默认网站根目录位置
        root html;

        #设定本虚拟主机的访问日志
        access_log  logs/nginx.access.log  main;

        #默认请求
        location / {
            
            #定义首页索引文件的名称
            index index.php index.html index.htm;   

        }

        # 定义错误提示页面
        error_page   500 502 503 504 /50x.html;
        location = /50x.html {
        }

        #静态文件,nginx本身处理
        location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            
            #过时30天,静态文件不怎么更新,过时能够设大一点,
            #若是频繁更新,则能够设置得小一点。
            expires 30d;
        }

        #PHP 脚本请求所有转发到 FastCGI处理. 使用FastCGI默认配置.
        location ~ .php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include fastcgi_params;
        }

        #禁止访问 .htxxx 文件
            location ~ /.ht {
            deny all;
        }

    }
}

 配置80端口

# Virtual Host configuration for arlingbc.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#

# 丢弃缺少 Host 头的请求
server {
       listen 80;
       return 444;
}

server {
       listen 80;
       listen [::]:80;
       server_name example.com www.example.com;

       # 定义服务器的默认网站根目录位置
       root /var/www/example/;
       
       # Add index.php to the list if you are using PHP
       index index.html index.htm index.nginx-debian.html;

       # access log file 访问日志
       access_log logs/nginx.access.log main;
       
       # 禁止访问隐藏文件
       # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
       location ~ /\. {
                deny all;
                access_log off;
                log_not_found off;
       }
    
       # 默认请求
       location / {
                # 首先尝试将请求做为文件提供,而后做为目录,而后回退到显示 404。
                # try_files 指令将会按照给定它的参数列出顺序进行尝试,第一个被匹配的将会被使用。
                # try_files $uri $uri/ =404;
      
                try_files $uri $uri/ /index.php?path_info=$uri&$args =404;
                access_log off;
                expires max;
       }
    
       # 静态文件,nginx 本身处理
       location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            
           #过时 30 天,静态文件不怎么更新,过时能够设大一点,
           #若是频繁更新,则能够设置得小一点。
           expires 30d;
       }
    
       # .php 请求
       location ~ \.php$ {
                try_files $uri =404;
                include /etc/nginx/fastcgi_params;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_intercept_errors on;
       }
    
      # PHP 脚本请求所有转发到 FastCGI 处理. 使用 FastCGI 默认配置.
      # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
      #
      #location ~ \.php$ {
      #       include snippets/fastcgi-php.conf;
      #
      #       # With php7.0-cgi alone:
      #       fastcgi_pass 127.0.0.1:9000;
      #       # With php7.0-fpm:
      #       fastcgi_pass unix:/run/php/php7.0-fpm.sock;
      #}
      
      # 拒绝访问. htaccess 文件,若是 Apache 的文档根与 nginx 的一致
      # deny access to .htaccess files, if Apache's document root
      # concurs with nginx's one
      #
      #location ~ /\.ht {
      #       deny all;
      #}
}

配置https 443端口

##
# 80 port
##

# 默认服务器,丢弃缺少 Host 头的请求
server {
       listen 80;
       return 444;
}

server {
        listen 80;
        listen [::]:80;
        sever_name example.com www.example.com;

        rewrite ^(.*)$ https://$host$1 permanent;  ## 端口转发
}

##
# 443 port
##
server {
    
    ##
    # 阿里云参考配置
    ##
    
    listen 443;
    listen [::]:443;
    server_name example.com www.example.com;
    
    root /var/www/example/;    # 为虚拟服务器指明文档的根目录
    index index.html index.htm; # 给定URL文件
    
    ##
    # 部署 HTTP 严格传输安全(HSTS)
    ##
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
    
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    gzip off;
    
    ##
    # SSL configuration
    ##
    
    ssl on;
    ssl_certificate   cert/certfile.pem;    # 证书
    ssl_certificate_key  cert/certfile.key; # 私钥
    ssl_session_timeout 5m; # 设置超时时间
    # 密码套件配置
    # 密码套件名称构成:密钥交换-身份验证-加密算法(算法-强度-模式)-MAC或PRF
    ssl_ciphers ECDHE-RSA-AES128-GCM- SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; 
    ssl_protocols TLSv1.2; # 设置 SSL/TSL 协议版本号
    ssl_prefer_server_ciphers on; # 控制密码套件优先级,让服务器选择要使用的算法套件
    ssl_buffer_size 1400; # 减小TLS缓冲区大小,能够显著减小首字节时间(《HTTPS权威指南》P416)
    
    ##
    # location configuration
    ##
    
    # ...
}

ngx_http_limit_conn_module 模块

http {
    # 最大链接数
    # 分配一个共享内存区域,大小为 10M,用于限制IP
    # 使用 $binary_remote_addr 变量, 能够将每条状态记录的大小减小到 64 个字节,这样 1M 的内存能够保存大约 16 千个 64 字节的记录。
    limit_conn_zone $binary_remote_addr zone=ips:10m;
    # 分配一个共享内存区域,大小为 10M,用于限制服务器链接数
    limit_conn_zone $server_name zone=servers:10m;
    
    # 设置日志记录级别
    # 当服务器由于频率太高拒绝或者延迟处理请求时能够记下相应级别的日志。
    limit_conn_log_level notice;

    server {
        # 限制每个IP地址访问限制10个链接
        limit_conn ips 10;
        
        # 服务器提供的最大链接数 1000
        limit_conn servers 1000;
    }
}

ngx_http_limit_req_module 模块

http {
    # 最大链接数
    # 分配一个共享内存区域,大小为 10M,限制下载链接数为1
    limit_conn_zone $binary_remote_addr zone=connections:10m;

    # 最大并发数,每秒请求数(r/s),每分钟请求数(r/m)
    # 分配一个设置最大并发数的内存区域,大小 10M,limit_req 限制以前的请求速率 1次/s。
    # 使用 $binary_remote_addr 变量, 能够将每条状态记录的大小减小到 64 个字节,这样 1M 的内存能够保存大约 16 千个 64 字节的记录。
    limit_req_zone $binary_remote_addr zone=requests:10m rate=1r/s;

    # 设置日志记录级别
    # 当服务器由于频率太高拒绝或者延迟处理请求时能够记下相应级别的日志。
    limit_req_log_level warn;

    # immediately release socket buffer memory on timeout
    reset_timedout_connection on;

    server {
    
        # 仅对 search URL 有效
        location /search {
            
            # 限制速率
            # 最大延迟请求数量 10 个,超过则返回状态码 503
            limit_req zone=requests burst=3 nodelay;
        }
        
        # 限制客户端带宽,
        # 策略:容许小文件自由下载,但对于大文件则启用这种限制
        location /downloads {
            # 首先限制客户端的下载链接数为1 
            limit_conn connections 1;

            # 下载完 1M 内容以后,启用 limit_rate 限制。
            limit_rate_after 1m;
            
            # 限制客户端下载下载内容的速率为 500k/s
            limit_rate 500k;
        }
    }
}

Nginx相关地址

 

源码:https://trac.nginx.org/nginx/browser

 

官网:http://www.nginx.org/

nginx从入门到精通:http://tengine.taobao.org/book/index.html

中文文档:http://www.nginx.cn/doc/

 

nginx强制使用https访问(http跳转到https)

nginx的rewrite方法

将全部的http请求经过rewrite重写到https上便可

server {
    listen    192.168.1.111:80;
    server_name    test.com;
    
    rewrite ^(.*)$    https://$host$1    permanent;

nginx的497状态码

error code 497

解释:当此虚拟站点只容许https访问时,当用http访问时nginx会报出497错误码

利用error_page命令将497状态码的连接重定向到https://test.com这个域名上

server {
    listen       192.168.1.11:443;    #ssl端口
    listen       192.168.1.11:80;    #用户习惯用http访问,加上80,后面经过497状态码让它自动跳到443端口
    server_name  test.com;
    #为一个server{......}开启ssl支持
    ssl                  on;
    #指定PEM格式的证书文件 
    ssl_certificate      /etc/nginx/test.pem; 
    #指定PEM格式的私钥文件
    ssl_certificate_key  /etc/nginx/test.key;
    
    #让http请求重定向到https请求    
    error_page 497    https://$host$uri?$args;

index.html刷新网页(上面两种耗服务器资源)

index.html(百度推荐方法)

<html>
<meta http-equiv="refresh" content="0;url=https://test.com/">
</html>
server {
    listen 192.168.1.11:80;
    server_name    test.com;
    
    location / {
                #index.html放在虚拟主机监听的根目录下
        root /srv/www/http.test.com/;
    }
        #将404的页面重定向到https的首页
    error_page    404    https://test.com/;
相关文章
相关标签/搜索