家喻户晓,Nginx 是 Apache服务不错的替代品。其特点是占有内存少,并发能力强,事实上 Nginx 的并发能力在同类型的网页服务器中体现较好,因而国内出名大厂例如:淘宝,京东,百度,新浪,网易,腾讯等等都在应用Nginx网站。

Nginx简介

Nginx 是开源、高性能、高牢靠的 Web 和反向代理服务器,而且反对热部署,同时也提供了 IMAP/POP3/SMTP 服务,能够不间断运行,提供热更新性能。占用内存少、并发能力强,最重要的是,Nginx 是收费的并能够商业化,配置应用都比较简单。

Nginx 特点
  • 高并发、高性能
  • 模块化架构使得它的扩展性十分好
  • 异步非阻塞的事件驱动模型这点和 Node.js 类似
  • 无需重启可不间断运行
  • 热部署、平滑降级
  • 齐全开源,生态好
Nginx 最重要的几个应用场景:
  • 动态资源服务
  • 反向代理服务,包含缓存、负载平衡等
  • API 服务,OpenResty

所以,明天民工哥就给大家整顿一份 Nginx的罕用配置清单,供大家学习与生产配置参考应用。次要包含以下三个方面:

  • 根底配置
  • 高级配置
  • 平安配置

根底配置

去掉不必的 Nginx 模块

./configure --without-module1 --without-module2 --without-module3例如:./configure --without-http_dav_module --withouthttp_spdy_module#注意事项:配置指令是由模块提供的。确保你禁用的模块不蕴含你须要应用的指令!在决定禁用模块之前,应该查看Nginx文档中每个模块可用的指令列表。

Nginx 版本的平滑降级与回滚

1分钟搞定 Nginx 版本的平滑降级与回滚

过程相干的配置

worker_processes 8;#Nginx 过程数,倡议依照CPU数目来指定,个别为它的倍数 (如,2个四核的CPU计为8)。worker_rlimit_nofile 65535;  #一个Nginx 过程关上的最多文件描述符数目worker_connections 65535;#每个过程容许的最多连接数

监听端口

server {        listen       80;   #监听端口        server_name  www.mingongge.com;  #域名信息        location / {            root   /www/www;   #网站根目录            index  index.html index.htm;  #默认首页类型            deny 192.168.2.11;   #禁止拜访的ip地址,能够为all            allow 192.168.3.44; #容许拜访的ip地址,能够为all        }        }          

小技巧补充:域名匹配的四种写法

准确匹配:server_name www.mingongge.com ;左侧通配:server_name *.mingongge.com ;右侧统配:server_name www.mingongge.* ;正则匹配:server_name ~^www\.mingongge\.*$ ;匹配优先级:准确匹配 > 左侧通配符匹配 > 右侧通配符匹配 > 正则表达式匹配

配置 Nginx 状态页面

[root@proxy ~]# cat /usr/local/nginx/conf/nginx.conf… …location /NginxStatus {      stub_status           on;      access_log            on;      auth_basic            "NginxStatus";      auth_basic_user_file  conf/htpasswd;        }… …[root@proxy ~]# /usr/local/nginx/sbin/nginx -s reload

Nginx 日志(拜访与谬误日志治理)

error_log  /var/log/nginx/error.log warn;#配置谬误日志的级别及存储目录events {    worker_connections  1024;}http {..................    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  /var/log/nginx/access.log main;    #配置拜访日志存储目录}

以上配置只是Nginx本身对于日志的根本配置,在理论生产环境中,咱们须要收集日志、剖析日志,才定更好的去定位问题,举荐给大家:超强干货!通过filebeat、logstash、rsyslog 几种形式采集 nginx 日志

http 相干的配置

http {    sendfile  on                  #高效传输文件的模式 肯定要开启    keepalive_timeout   65        #客户端服务端申请超时工夫 }

动态资源配置

server {  listen 80;  server_name mingongge.com;  location /static {        root /wwww/web/web_static_site;   }}

也能够应用上面的办法

location /image {   alias /web/nginx/static/image/;  }留神:应用alias开端肯定要增加/,并且它只能位于location中

反向代理

比方生产环境(同一台服务中)有不同的我的项目,这个就比拟实用了,用反向代理去做请示转发。

http {.............    upstream product_server{        127.0.0.1:8081;    }    upstream admin_server{        127.0.0.1:8082;    }    upstream test_server{        127.0.0.1:8083;    }server {        #默认指向product的server  location / {      proxy_pass http://product_server;      }  location /product/{      proxy_pass http://product_server;     }  location /admin/ {      proxy_pass http://admin_server;     }  location /test/ {      proxy_pass http://test_server;      }    }}

更多对于 Nginx 实际:location 门路匹配

负载平衡

upstream server_pools {   server 192.168.1.11:8880   weight=5;  server 192.168.1.12:9990   weight=1;  server 192.168.1.13:8989   weight=6;  #weigth参数示意权值,权值越高被调配到的几率越大}server {    listen 80;   server_name mingongge.com;  location / {      proxy_pass http://server_pools;    }}

代理相干的其它配置

proxy_connect_timeout 90;  #nginx跟后端服务器连贯超时工夫(代理连贯超时)proxy_send_timeout 90;     #后端服务器数据回传工夫(代理发送超时)proxy_read_timeout 90;     #连贯胜利后,后端服务器响应工夫(代理接管超时)proxy_buffer_size 4k;      #代理服务器(nginx)保留用户头信息的缓冲区大小proxy_buffers 4 32k;      #proxy_buffers缓冲区proxy_busy_buffers_size 64k;     #高负荷下缓冲大小(proxy_buffers*2)proxy_temp_file_write_size 64k;  #设定缓存文件夹大小proxy_set_header Host $host; proxy_set_header X-Forwarder-For $remote_addr;  #获取客户端实在IP

高级配置

重定向配置

location / {    return 404; #间接返回状态码}location / {    return 404 "pages not found";    #返回状态码 + 一段文本}location / {    return 302 /blog ;    #返回状态码 + 重定向地址}location / {    return https://www.mingongge.com ;    #返回重定向地址  }

示例如下

server { listen 80;server_name www.mingongge.com;return 301 http://mingongge.com$request_uri;}server {listen 80; server_name www.mingongge.com; location /cn-url {    return 301 http://mingongge.com.cn;    }}server{  listen 80;  server_name mingongge.com; # 要在本地hosts文件进行配置  root html;  location /search {   rewrite ^/(.*) https://www.mingongge.com redirect;  }    location /images {   rewrite /images/(.*) /pics/$1;  }    location /pics {   rewrite /pics/(.*) /photos/$1;  }    location /photos {    }}

设置缓冲区容量下限

这样的设置能够阻止缓冲区溢出攻打(同样是Server模块)

client_body_buffer_size 1k;client_header_buffer_size 1k;client_max_body_size 1k;large_client_header_buffers 2 1k;#设置后,不论多少HTTP申请都不会使服务器零碎的缓冲区溢出了

限度最大连接数

在http模块内server模块外配置limit_conn_zone,配置连贯的IP,在http,server或location模块配置limit_conn,能配置IP的最大连接数。

limit_conn_zone $binary_remote_addr zone=addr:5m;limit_conn addr 1;

Gzip压缩

gzip_types  #压缩的文件类型 text/plain text/css  application/json  application/x-javascript  text/xml application/xml  application/xml+rss  text/javascriptgzip on;#采纳gzip压缩的模式发送数据gzip_disable "msie6"#为指定的客户端禁用gzip性能gzip_static;#压缩前查找是否有事后gzip解决过的资源gzip_proxied any;#容许或者禁止压缩基于申请和响应的响应流gzip_min_length  1000;#设置对数据启用压缩的起码字节数gzip_comp_level 6;#设置数据的压缩等级

缓存配置

open_file_cache#指定缓存最大数目以及缓存的工夫open_file_cache_valid#在open_file_cache中指定检测正确信息的间隔时间open_file_cache_min_uses   #定义了open_file_cache中指令参数不流动工夫期间里最小的文件数open_file_cache_errors     #指定了当搜寻一个文件时是否缓存错误信息location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$#指定缓存文件的类型        {        expires 3650d;               #指定缓存工夫        }        location ~ .*\.(js|css)?$        {        expires 3d;                             }

SSL 证书配及跳转HTTPS配置

server {      listen 192.168.1.250:443 ssl;      server_tokens off;      server_name mingonggex.com www.mingonggex.com;      root /var/www/mingonggex.com/public_html;      ssl_certificate /etc/nginx/sites-enabled/certs/mingongge.crt;      ssl_certificate_key /etc/nginx/sites-enabled/certs/mingongge.key;      ssl_protocols TLSv1 TLSv1.1 TLSv1.2;}# Permanent Redirect for HTTP to HTTPSserver {  listen 80;  server_name mingongge.com; return 301  https://$server_name$request_uri;}

流量镜像性能

location / {    mirror /mirror;    proxy_pass http://backend;}location = /mirror {    internal;    proxy_pass http://test_backend$request_uri;}

限流性能

流量限度配置两个次要的指令,limit_req_zonelimit_req

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;server {    location /login/ {        limit_req zone=mylimit;        proxy_pass http://my_upstream;    }}

更多、更具体的限流配置请参考:葵花宝典!一文搞定 Nginx 限流配置

Nginx罕用的内置变量

平安配置

禁用server_tokens项

server_tokens在关上的状况下会使404页面显示Nginx的以后版本号。这样做显然不平安,因为黑客会利用此信息尝试相应Nginx版本的破绽。只须要在nginx.conf中http模块设置server_tokens off即可,例如:

server {    listen 192.168.1.250:80;    Server_tokens off;    server_name mingongge.com www.mingongge.com;    access_log /var/www/logs/mingongge.access.log;    error_log /var/www/logs/mingonggex.error.log error;    root /var/www/mingongge.com/public_html;    index index.html index.htm;}#重启Nginx后失效:

禁止非法的HTTP User Agents

User Agent是HTTP协定中对浏览器的一种标识,禁止非法的User Agent能够阻止爬虫和扫描器的一些申请,避免这些申请大量耗费Nginx服务器资源。

为了更好的保护,最好创立一个文件,蕴含不冀望的user agent列表例如/etc/nginx/blockuseragents.rules蕴含如下内容:

map $http_user_agent $blockedagent {    default 0;    ~*malicious 1;    ~*bot 1;    ~*backdoor 1;    ~*crawler 1;    ~*bandit 1;}

而后将如下语句放入配置文件的server模块内

include /etc/nginx/blockuseragents.rules;并退出if语句设置阻止后进入的页面:

阻止图片外链

location /img/ {      valid_referers none blocked 192.168.1.250;        if ($invalid_referer) {          return 403;      }}

封杀歹意拜访

挺带劲!通过 Nginx 来实现封杀歹意拜访

禁掉不须要的 HTTP 办法

一些web站点和利用,能够只反对GET、POST和HEAD办法。在配置文件中的 serve r模块退出如下办法能够阻止一些坑骗攻打

if ($request_method !~ ^(GET|HEAD|POST)$) {    return 444;}

禁止 SSL 并且只关上 TLS

尽量避免应用SSL,要用TLS代替,以下配置能够放在Server模块内

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

通过这一系列的配置之后,置信你的Nginx服务器足够应酬理论生产需要了。

也欢送大家踊跃留言补充这份罕用配置清单,以便它更残缺、更欠缺。