开发者社区> shaonbean> 正文

Nginx源码安装及调优配置

简介:
+关注继续查看
由于Nginx本身的一些优点,轻量,开源,易用,越来越多的公司使用nginx作为自己公司的web应用服务器,本文详细介绍nginx源码安装的同时并对nginx进行优化配置。

Nginx源码安装及调优配置Nginx源码安装及调优配置

Nginx编译前的优化
[root@linuxprobe ~]# wget http://nginx.org/download/nginx-1.10.1.tar.gz
[root@linuxprobe ~]# tar xvf nginx-1.10.1.tar.gz -C /usr/local/src/
[root@linuxprobe ~]# cd /usr/local/src/nginx-1.10.1/

编译前的优化主要是用来修改程序名等等,例如:

[root@linuxprobe nginx-1.10.1]# curl -I http://www.baidu.com
……
Server: bfe/1.0.8.14
……
[root@linuxprobe nginx-1.10.1]# curl -I http://www.sina.com.cn
……
Server: nginx
……
[root@linuxprobe nginx-1.10.1]# curl -I http://www.linuxprobe.com
HTTP/1.1 200 OK
Server: nginx/1.10.1 #我们目标是将nginx更改名字
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/5.6.29
Set-Cookie: PHPSESSID=smm0i6u4f9v7bj0gove79ja1g7; path=/
Cache-Control: no-cache
Date: Mon, 07 Seq 2016 06:09:11 GMT
[root@linuxprobe nginx-1.10.1]# vim src/core/nginx.h

 

  • 目的更改源码隐藏软件名称和版本号

 

 

#define NGINX_VERSION "nginx_stable" #此行修改的是你想要的版本号

#define NGINX_VER "linuxprobe/" NGINX_VERSION #此行修改的是你想修改的软件名称

[root@linuxprobe nginx-1.10.1]# vim +49 src/http/ngx_http_header_filter_module.c

 

  • 修改HTTP头信息中的connection字段,防止回显具体版本号

 

 

拓展:通用http头域

通用头域包含请求和响应消息都支持的头域,通用头域包含Cache-Control、 Connection、Date、Pragma、Transfer-Encoding、Upgrade、Via。对通用头域的扩展要求通讯双方都支持此扩展,如果存在不支持的通用头域,一般将会作为实体头域处理。那么也就是说有部分设备,或者是软件,能获取到connection,部分不能,要隐藏就要彻底!

static char ngx_http_server_string[] = "Server: LinuxprobeWeb" CRLF;

[root@linuxprobe nginx-1.10.1]# vim +29 src/http/ngx_http_special_response.c

 

  • 定义了http错误码的返回

 

 

有时候我们页面程序出现错误,Nginx会代我们返回相应的错误代码,回显的时候,会带上nginx和版本号,我们把他隐藏起来

static u_char ngx_http_error_full_tail[] =
"<hr><center>" NGINX_VER "</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;

修改后

static u_char ngx_http_error_tail[] =
"<hr><center>LinuxprobeWeb</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;
Nginx正式安装
一键安装相关依赖包
[root@linuxprobe nginx-1.10.1]# yum install gcc gcc-c++ autoconf automake zlib zlib-devel openssl openssl-devel -y
安装pcre依赖

#本地下载pcre上传到服务器

[root@linuxprobe]# tar zxvf /usr/local/src/pcre-8.36.tar.gz -C /usr/local/src/
[root@linuxprobe nginx-1.10.1]# cd  /usr/local/src/pcre-8.36
[root@linuxprobe nginx-1.10.1]# ./configure && make && make install
[root@linuxprobe nginx-1.10.1]# ./configure --prefix=/usr/local/nginx --with-http_dav_module --with-http_stub_status_module --with-http_addition_module --with-http_sub_module --with-http_flv_module --with-http_mp4_module --with-pcre=/usr/local/src/pcre-8.36 --with-openssl=/usr/include/openssl
注意:TCP_FASTOPEN 只在 3.7.1 以及更新的 Linux 内核版本才支持
--with-http_dav_module             #启用支持(增加PUT,DELETE,MKCOL:创建集合,COPY和MOVE方法)默认关闭,需要编译开启
--with-http_stub_status_module     #启用支持(获取Nginx上次启动以来的工作状态)
--with-http_addition_module        #启用支持(作为一个输出过滤器,支持不完全缓冲,分部分相应请求)
--with-http_sub_module             #启用支持(允许一些其他文本替换Nginx相应中的一些文本)
--with-http_flv_module             #启用支持(提供支持flv视频文件支持)
--with-http_mp4_module             #启用支持(提供支持mp4视频文件支持,提供伪流媒体服务端支持)
--with-pcre=/usr/local/src/pcre-8.36            #需要注意,这里指的是源码,用#./configure --help |grep pcre查看帮助
[root@linuxprobe nginx-1.10.1]# make && make install
#Nginx安装路径。如果没有指定,默认为 /usr/local/nginx。
--prefix=PATH       #Nginx可执行文件安装路径。只能安装时指定,如果没有指定,默认为PATH/sbin/nginx。
--sbin-path=PATH    #在没有给定-c选项下默认的nginx.conf的路径。如果没有指定,默认为PATH/conf/nginx.conf。 
--conf-path=PATH    #在nginx.conf中没有指定pid指令的情况下,默认的nginx.pid的路径。如果没有指定,默认为 PATH/logs/nginx.pid。
--pid-path=PATH     #nginx.lock文件的路径。
--lock-path=PATH    #在nginx.conf中没有指定error_log指令的情况下,默认的错误日志的路径。如果没有指定,默认为 PATH/logs/error.log。
--error-log-path=PATH    #在nginx.conf中没有指定access_log指令的情况下,默认的访问日志的路径。如果没有指定,默认为 PATH/logs/access.log。
--http-log-path=PATH     #在nginx.conf中没有指定user指令的情况下,默认的nginx使用的用户。如果没有指定,默认为 nobody。
--user=USER       #在nginx.conf中没有指定user指令的情况下,默认的nginx使用的组。如果没有指定,默认为 nobody。
--group=GROUP     #指定编译的目录
--builddir=DIR    #启用 rtsig 模块
--with-rtsig_module    #允许或不允许开启SELECT模式,如果configure没有找到合适的模式,比如,kqueue(sun os)、epoll(linux kenel 2.6+)、rtsig(实时信号)
--with-select_module(--without-select_module)    #允许或不允许开启POLL模式,如果没有合适的,则开启该模式。
--with-poll_module(--without-poll_module)        #开启HTTP SSL模块,使NGINX可以支持HTTPS请求。这个模块需要已经安装了OPENSSL,在DEBIAN上是libssl-dev

--with-http_ssl_module         #启用ngx_http_ssl_module
--with-http_realip_module      #启用 ngx_http_realip_module
--with-http_addition_module    #启用 ngx_http_addition_module
--with-http_sub_module    #启用 ngx_http_sub_module
--with-http_dav_module    #启用 ngx_http_dav_module
--with-http_flv_module    #启用 ngx_http_flv_module
--with-http_stub_status_module    #启用 "server status" 页
--without-http_charset_module     #禁用 ngx_http_charset_module
--without-http_gzip_module        #禁用 ngx_http_gzip_module. 如果启用,需要 zlib 。
--without-http_ssi_module         #禁用 ngx_http_ssi_module
--without-http_userid_module      #禁用 ngx_http_userid_module
--without-http_access_module      #禁用 ngx_http_access_module
--without-http_auth_basic_module  #禁用 ngx_http_auth_basic_module
--without-http_autoindex_module   #禁用 ngx_http_autoindex_module
--without-http_geo_module         #禁用 ngx_http_geo_module
--without-http_map_module         #禁用 ngx_http_map_module
--without-http_referer_module     #禁用 ngx_http_referer_module
--without-http_rewrite_module     #禁用 ngx_http_rewrite_module. 如果启用需要 PCRE 。
--without-http_proxy_module       #禁用 ngx_http_proxy_module
--without-http_fastcgi_module     #禁用 ngx_http_fastcgi_module
--without-http_memcached_module   #禁用 ngx_http_memcached_module
--without-http_limit_zone_module  #禁用 ngx_http_limit_zone_module
--without-http_empty_gif_module   #禁用 ngx_http_empty_gif_module
--without-http_browser_module     #禁用 ngx_http_browser_module
--without-http_upstream_ip_hash_module   #禁用 ngx_http_upstream_ip_hash_module
--with-http_perl_module -         #启用 ngx_http_perl_module
--with-perl_modules_path=PATH     #指定 perl 模块的路径
--with-perl=PATH        #指定 perl 执行文件的路径
--http-log-path=PATH    #Set path to the http access log
--http-client-body-temp-path=PATH    #Set path to the http client request body temporary files
--http-proxy-temp-path=PATH          #Set path to the http proxy temporary files
--http-fastcgi-temp-path=PATH        #Set path to the http fastcgi temporary files
--without-http                 #禁用 HTTP server
--with-mail                    #启用 IMAP4/POP3/SMTP 代理模块
--with-mail_ssl_module         #启用 ngx_mail_ssl_module
--with-cc=PATH                 #指定 C 编译器的路径
--with-cpp=PATH                #指定 C 预处理器的路径
--with-cc-opt=OPTIONS #
--with-ld-opt=OPTIONS #Additional parameters passed to the linker. With the use of the system library PCRE in FreeBSD, it is necessary to indicate --with-ld-opt="-L /usr/local/lib".
--with-cpu-opt=CPU        #为特定的CPU编译,有效的值包括:pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64
--without-pcre            #禁止PCRE库的使用。同时也会禁止 HTTP rewrite 模块。在 "location" 配置指令中的正则表达式也需要 PCRE 。
--with-pcre=DIR           #指定 PCRE 库的源代码的路径。
--with-pcre-opt=OPTIONS   #设置PCRE的额外编译选项。
--with-md5=DIR            #使用MD5汇编源码。
--with-md5-opt=OPTIONS    #Set additional options for md5 building.
--with-md5-asm            #Use md5 assembler sources.
--with-sha1=DIR           #Set path to sha1 library sources.
--with-sha1-opt=OPTIONS   #Set additional options for sha1 building.
--with-sha1-asm           #Use sha1 assembler sources.
--with-zlib=DIR           #Set path to zlib library sources.
--with-zlib-opt=OPTIONS   #Set additional options for zlib building.
--with-zlib-asm=CPU       #Use zlib assembler sources optimized for specified CPU, valid values are: pentium, pentiumpro
--with-openssl=DIR        #Set path to OpenSSL library sources
--with-openssl-opt=OPTIONS #Set additional options for OpenSSL building
--with-debug              #启用调试日志
--add-module=PATH         #Add in a third-party module found in directory PATH
启动nginx
[root@linuxprobe nginx-1.10.1]# /usr/local/nginx/sbin/nginx
[root@linuxprobe nginx-1.10.1]# netstat -antup | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 52553/nginx

测试是否隐藏了版本和软件名

[root@linuxprobe nginx-1.10.1]# cd
[root@linuxprobe ~]# curl -I http://127.0.0.1

Nginx源码安装及调优配置Nginx源码安装及调优配置

错误代码测试(尽量使用firefox或者类360浏览器)

Nginx源码安装及调优配置Nginx源码安装及调优配置Nginx运行用户

[root@linuxprobe~]# useradd -M -s /sbin/nologin nginx //修改nginx默认运行用户
[root@linuxprobe ~]# ps -aux | grep nginx //默认是nobody用户
nobody 52554 0.0 0.1 22660 1568 ? S 14:39 0:00 nginx: worker process
[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf
user nginx;
[root@linuxprobe ~]# /usr/local/nginx/sbin/nginx -s reload
[root@linuxprobe ~]# ps -aux | grep nginx
nginx 52555 0.0 0.1 22660 1568 ? S 14:39 0:00 nginx: worker process

在这里我们还可以看到在查看的时候,work进程是nginx用户了,但是master进程还是root

其中,master是监控进程,也叫主进程,work是工作进程,部分还有cache相关进程,关系如图:

Nginx源码安装及调优配置Nginx源码安装及调优配置

所以我们可以master监控进程使用root,可以是降级使用普通用户,如果都是用普用户,注意编译安装的时候,是用普通用户执行,sudo方式操作!可以直接理解为master是管理员,work进程才是为用户提供服务的!

Nginx运行进程个数,一般我们设置CPU的核心或者核心数x2,如果你不了解,top命令之后按1也可以看出来(一般直接追到线程即可)

[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf
worker_processes 2;
[root@linuxprobe ~]# /usr/local/nginx/sbin/nginx -s reload
[root@linuxprobe ~]# ps -axu | grep nginx
nginx 52686 0.0 0.1 22668 1300 ? S 15:10 0:00 nginx: worker process
nginx 52687 0.0 0.1 22668 1376 ? S 15:10 0:00 nginx: worker process

Nginx运行CPU亲和力(这个要根据你的CPU线程数配置)

比如4核4线程配置

[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;

比如8核8线程配置

worker_processes 8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

那么如果我是4线程的CPU,我只想跑两个进程呢?

worker_processes 2;
worker_cpu_affinity 0101 1010;

意思就似乎我开启了第一个和第三个内核,第二个和第四个内核,两个进程分别在这两个组合上轮询!worker_processes最多开启8个,8个以上性能提升不会再提升了,而且稳定性变得更低,所以8个进程够用了。

Nginx最多可以打开文件数 worker_rlimit_nofile 65535;

这个指令是指当一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(ulimit -n)与nginx进程数相除,但是nginx分配请求并不是那么均匀,所以最好与ulimit -n的值保持一致。

Nginx事件处理模型

events {
use epoll;
worker_connections 1024;
}

知道在linux下nginx采用epoll事件模型,处理效率高,关于epoll的时间处理其他只是,可以自行百度,了解即可!

Work_connections是单个进程允许客户端最大连接数,这个数值一般根据服务器性能和内存来制定,也就是单个进程最大连接数,实际最大值就是work进程数乘以这个数,如何设置,可以根据设置一个进程启动所占内存,top -u nginx,但是实际我们填入一个65535,足够了,这些都算并发值,一个网站的并发达到这么大的数量,也算一个大站了!

开启高效传输模式

http {

include mime.types;
default_type application/octet-stream;
……
sendfile on;
#tcp_nopush on;
……
 Include mime.types;   媒体类型
 default_type application/octet-stream;   默认媒体类型足够
 sendfile on;   开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
 tcp_nopush on;   必须在sendfile开启模式才有效,防止网路阻塞,积极的减少网络报文段的数量

连接超时时间

主要目的是保护服务器资源,CPU,内存,控制连接数,因为建立连接也是需要消耗资源的,TCP的三次握手四次挥手等,我们一般断掉的是那些建立连接但是不做事儿,也就是我建立了链接开始,但是后续的握手过程没有进行,那么我们的链接处于等待状态的,全部断掉!

同时我们也希望php建议短链接,消耗资源少

Java建议长链接,消耗资源少

keepalive_timeout 60;
tcp_nodelay on;
client_header_timeout 15;
client_body_timeout 15;
send_timeout 15;
keepalived_timeout 客户端连接保持会话超时时间,超过这个时间,服务器断开这个链接
tcp_nodelay;也是防止网络阻塞,不过要包涵在keepalived参数才有效
client_header_timeout 客户端请求头读取超时时间,如果超过这个时间没有发送任何数据,nginx将返回request time out的错误
client_body_timeout 客户端求主体超时时间,超过这个时间没有发送任何数据,和上面一样的错误提示
send_timeout 响应客户端超时时间,这个超时时间仅限于两个活动之间的时间,如果超哥这个时间,客户端没有任何活动,nginx关闭连接

文件上传大小限制

我们知道PHP可以修改上传文件大小限制,nginx也可以修改

http {
……
client_max_body_size 10m;
Fastcgi调优

Nginx没有配置factcgi,你使用nginx是一个失败的方法,配置之前。了解几个概念:

Cache:  写入缓存区
Buffer: 读取缓存区
Fastcgi  是静态服务和动态服务的一个接口
fastcgi_connect_timeout 300;     #指定链接到后端FastCGI的超时时间。
fastcgi_send_timeout 300;        #向FastCGI传送请求的超时时间,这个值是指已经完成两次握手后向FastCGI传送请求的超时时间。
fastcgi_read_timeout 300;        #指定接收FastCGI应答的超时时间,这个值是指已经完成两次握手后接收FastCGI应答的超时时间。
fastcgi_buffer_size 64k;         #指定读取FastCGI应答第一部分需要用多大的缓冲区,这个值表示将使用1个64KB的缓冲区读取应答的第一部分(应答头),可以设置为gastcgi_buffers选项指定的缓冲区大小。
fastcgi_buffers 4 64k;          #指定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答请求,如果一个php脚本所产生的页面大小为256KB,那么会分配4个64KB的缓冲区来缓存,如果页面大小大于256KB,那么大于256KB的部分会缓存到fastcgi_temp指定的路径中,但是这并不是好方法,因为内存中的数据处理速度要快于磁盘。一般这个值应该为站点中php脚本所产生的页面大小的中间值,如果站点大部分脚本所产生的页面大小为256KB,那么可以把这个值设置为“8 16K”、“4 64k”等。
fastcgi_busy_buffers_size 128k;      #建议设置为fastcgi_buffer的两倍,繁忙时候的buffer
fastcgi_temp_file_write_size 128k;   #在写入fastcgi_temp_path时将用多大的数据库,默认值是fastcgi_buffers的两倍,设置上述数值设置小时若负载上来时可能报502Bad Gateway
fastcgi_cache aniu_ngnix;        #表示开启FastCGI缓存并为其指定一个名称。开启缓存非常有用,可以有效降低CPU的负载,并且防止502的错误放生,但是开启缓存也可能会引起其他问题,要很据具体情况选择
fastcgi_cache_valid 200 302 1h;  #用来指定应答代码的缓存时间,实例中的值表示将2000和302应答缓存一小时,要和fastcgi_cache配合使用
fastcgi_cache_valid 301 1d;      #将301应答缓存一天
fastcgi_cache_valid any 1m;      #将其他应答缓存为1分钟
fastcgi_cache_min_uses 1;        #请求的数量
fastcgi_cache_path               #定义缓存的路径

修改nginx.conf配置文件,在http标签中添加如下:

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
#fastcgi_temp_path /data/ngx_fcgi_tmp;
fastcgi_cache_path /opt/ngx_fcgi_cache levels=2:2
keys_zone=ngx_fcgi_cache:512m
inactive=1d max_size=40g;

缓存路径,levels目录层次2级,定义了一个存储区域名字,缓存大小,不活动的数据在缓存中多长时间,目录总大小

在server location标签添加如下:

location ~ .*\.(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_cache ngx_fcgi_cache;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_key http://$host$request_uri;
}

fastcgi cache官方文档:http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache

gzip调优

使用gzip压缩功能,可能为我们节约带宽,加快传输速度,有更好的体验,也为我们节约成本,所以说这是一个重点

Nginx启用压缩功能需要你来ngx_http_gzip_module模块,apache使用的是mod_deflate

一般我们需要压缩的内容有:文本,js,html,css,对于图片,视频,flash什么的不压缩,同时也要注意,我们使用gzip的功能是需要消耗CPU的!

gzip on;     #开启压缩功能
gzip_min_length 1k;    #设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取,默认值是0,不管页面多大都进行压缩,建议设置成大于1K,如果小与1K可能会越压越大。
gzip_buffers 4 32k;        #压缩缓冲区大小,表示申请4个单位为32K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。
gzip_http_version 1.1;     #压缩版本(默认1.1,前端为squid2.5时使用1.0)用于设置识别HTTP协议版本,默认是1.1,目前大部分浏览器已经支持GZIP解压,使用默认即可
gzip_comp_level 9;         #压缩比例,用来指定GZIP压缩比,1压缩比最小,处理速度最快,9压缩比最大,传输速度快,但是处理慢,也比较消耗CPU资源。
gzip_types text/css text/xml application/javascript;      #用来指定压缩的类型,‘text/html’类型总是会被压缩。
gzip_vary on;        #vary header支持,改选项可以让前端的缓存服务器缓存经过GZIP压缩的页面,例如用Squid缓存经过nginx压缩的数据

那么配置压缩的过程中,会有一下参数

gzip on;
gzip_min_length 1k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 9;
gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/xml+rss;
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_disable "MSIE [1-6]\.";
expires缓存调优

缓存,主要针对于图片,css,js等元素更改机会比较少的情况下使用,特别是图片,占用带宽大,我们完全可以设置图片在浏览器本地缓存365d,css,js,html可以缓存个10来天,这样用户第一次打开加载慢一点,第二次,就非常快乐!缓存的时候,我们需要将需要缓存的拓展名列出来!

Expires缓存配置在server字段里面

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 3650d;
}
location ~ .*\.(js|css)?$
{
expires 30d;
}

同时也可以对目录及其进行判断:

location ~ ^/(images|javascript|js|css|flash|media|static)/ {
expires 360d;
}
location ~(robots.txt) {
expires 7d;
break;
}

expire功能优点
(1)expires可以降低网站购买的带宽,节约成本
(2)同时提升用户访问体验
(3)减轻服务的压力,节约服务器成本,甚至可以节约人力成本,是web服务非常重要的功能。

expire功能缺点:

被缓存的页面或数据更新了,用户看到的可能还是旧的内容,反而影响用户体验。

解决办法:

第一个 缩短缓存时间,例如:1天,不彻底,除非更新频率大于1天

第二个 对缓存的对象改名

a.图片,附件一般不会被用户修改,如果用户修改了,实际上也是更改文件名重新传了而已

b.网站升级对于js,css元素,一般可以改名,把css,js,推送到CDN。

网站不希望被缓存的内容

1)广告图片

2)网站流量统计工具

3)更新频繁的文件(google的logo)

[root@linuxprobe ~]# cd /usr/local/nginx/logs/

日志优化的目的,是为了一天日志一压缩,焚天存放,超过10天的删除

创建日志切割脚本

//每天日志分割脚本

[root@linuxprobe logs]# vim cut_nginx_log.sh
#!/bin/bash
######################################
#function:cut nginx log files
#author: shaon
######################################
#set the path to nginx log files
log_files_path="/usr/local/nginx/logs"
log_files_dir=${log_files_path}/$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
log_files_dir=${log_files_path}/$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
#set nginx log files you want to cut
log_files_name=(access error)
#set the path to nginx.
nginx_sbin="/usr/local/nginx/sbin/nginx"
#Set how long you want to save
save_days=30
############################################
#Please do not modify the following script #
############################################
mkdir -p $log_files_dir
log_files_num=${#log_files_name[@]}

#cut nginx log files
for((i=0;i<$log_files_num;i++));do
mv ${log_files_path}/${log_files_name[i]}.log ${log_files_dir}/${log_files_name[i]}_$(date -d "yesterday" +"%Y%m%d").log
done ays -exec rm -rf {}
#delete 30 days ago nginx log files
find $log_files_path -mtime +$save_days -exec rm -rf {} \;

健康检查的日志,不输入到log中,这些日志没有意义,我们分析的话只需要分析访问日志,看看一些页面链接,如200,301,404的状态吗,在SEO中很重要,而且我们统计PV是页面计算,这些都没有意义,反而消耗了磁盘IO,降低了服务器性能,我们可以屏蔽这些如图片,js,css这些不宜变化的内容

[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf
location ~ .*\.(js|jpg|jpeg|JPG|JPEG|css|bmp|gif|GIF)$ {
access_log off;
}

日志目录权限优化

[root@linuxprobe ~]# chown -R root:root /usr/local/nginx/logs
[root@linuxprobe ~]# chmod 700 /usr/local/nginx/logs

日志格式优化

#vim /usr/local/nginx/conf/nginx.conf
log_format access ‘$remote_addr – $remote_user [$time_local] “$request” ‘‘$status $body_bytes_sent “$http_referer” ‘‘”$http_user_agent” $http_x_forwarded_for’;

其中,各个字段的含义如下:

1.$remote_addr  与$http_x_forwarded_for 用以记录客户端的ip地址;
2.$remote_user :    用来记录客户端用户名称;
3.$time_local :     用来记录访问时间与时区;
4.$request :        用来记录请求的url与http协议;
5.$status :         用来记录请求状态;成功是200,
6.$body_bytes_s ent :记录发送给客户端文件主体内容大小;
7.$http_referer :    用来记录从那个页面链接访问过来的;
8.$http_user_agent : 记录客户端浏览器的相关信息;

目录文件访问控制

主要用在禁止目录下指定文件被访问,当然也可以禁止所有文件被访问!一般什么情况下用?比如是有存储共享,这些文件本来都只是一下资源文件,那么这些资源文件就不允许被执行,如sh.py,pl,php等等

例如:禁止访问images下面的php程序文件

location ~ ^/images/.*\.(php|php5|.sh|.py|.py)$ {
deny all;
}
[root@linuxprobe ~]# /usr/local/nginx/sbin/nginx -s reload
[root@linuxprobe ~]# mkdir /usr/local/nginx/html/images
[root@linuxprobe ~]# echo "" > /usr/local/nginx/html/images/index.php

测试访问
Nginx源码安装及调优配置Nginx源码安装及调优配置

多目录组合配置方法

location ~ ^/images/(attachment|avatar)/.*\.(php|php5|.sh|.py|.py)$ {
deny all;
}

配置nginx禁止访问*.txt文件

[root@linuxprobe ~]# echo "hello,linuxprobe" > /usr/local/nginx/html/test.txt

Nginx源码安装及调优配置Nginx源码安装及调优配置

配置规则,禁止访问

[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf //server字段中
location ~* \.(txt|doc)$ {
if ( -f $request_filename) {
root /usr/local/nginx/html;
break;
}
deny all;
}
[root@linuxprobe ~]# /usr/local/nginx/sbin/nginx -s reload

Nginx源码安装及调优配置Nginx源码安装及调优配置

当然,可以重定向到某一个URL

[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf
location ~* \.(txt|doc)$ {
if ( -f $request_filename) {
root /usr/local/nginx/html;
rewrite ^/(.*)$ http://www.linuxprobe.com last;
break;
}
}

对目录进行限制的方法

[root@linuxprobe ~]# mkdir -p /usr/local/nginx/html/{linuxprobe,1mcloud}
[root@linuxprobe ~]# echo linuxprobe > /usr/local/nginx/html/linuxprobe/index.html
[root@linuxprobe ~]# echo 1mcloud > /usr/local/nginx/html/1mcloud/index.html
[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf
location /linuxprobe/ { return 404 ; }
location /1mcloud/ { return 403 ; }
测试返回结果

Nginx源码安装及调优配置Nginx源码安装及调优配置
Nginx源码安装及调优配置Nginx源码安装及调优配置

上面是直接给了反馈的状态吗,也可以通过匹配deny all方式做

[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf
location ~ ^/(linuxprobe)/ {
deny all;
}
[root@linuxprobe ~]# /usr/local/nginx/sbin/nginx -s reload

Nginx源码安装及调优配置Nginx源码安装及调优配置

来源访问控制

这个需要ngx_http_access_module模块支持,不过,默认会安装

[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf //写法类似Apache
location ~ ^/(linuxprobe)/ {
allow 192.168.1.0/24;
deny all;
}

Nginx源码安装及调优配置Nginx源码安装及调优配置
接着上面的实验,就可以访问了,下面是针对整个网站的写法,对/限制就OK

location / {
allow 192.168.1.0/24;
deny all;
}

当然可以写IP,可以写IP段,但是注意次序,上下匹配

同时,也可以通过if语句控制,给以友好的错误提示

if ( $remote_addr = 10.1.1.55 ) {
return 404;
}

#此处remote_addr地址为当前编辑文档的系统ip地址
Nginx源码安装及调优配置Nginx源码安装及调优配置

IP和301优化

有时候,我们发现访问网站的时候,使用IP也是可以得,我们可以把这一层给屏蔽掉,让其直接反馈给403,也可以做跳转

跳转的做法:

server {
listen 80 default_server;
server_name _;
rewrite ^ http://www.linuxprobe.com$request_uri?;
}

403反馈的做法

server {
listen 80 default_server;
server_name _;
return 403;
}

301跳转的做法

#如我们域名一般在解析的过程中,linuxprobe.com一般会跳转到www.linuxprobe.com,记住修改本地hosts

server {
listen 80;
root /usr/share/nginx/html/;
server_name www.linuxprobe.com linuxprobe.com;
if ($host = 'a.com' ) {
rewrite ^/(.*)$ www.linuxprobe.com/$1 permanent;
}
防盗链

防止别人直接从你网站引用图片等链接,消耗了你的资源和网络流量,那么我们的解决办法由几种:

1:水印,品牌宣传,你的带宽,服务器足够

2:防火墙,直接控制,前提是你知道IP来源

3:防盗链策略

下面的方法是直接给予404的错误提示

location ~* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
valid_referers none blocked *.linuxprobe,com linuxprobe.com;
if ($invalid_referer) {
return 404;
}

同时,我们也可以设置一个独有的,图片比较小的,来做rewrite跳转

location ~* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
valid_referers none blocked *.a.com a.com;
if ($invalid_referer) {
rewrite ^/ http://www.linuxprobe.com/img/nolink.png;
}

错误页面的提示

对于自定义的错误页面,我们只需要将errorpage写入到配置文件

error_page 404 /404.html;

内部身份验证

[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf
location /linuxprobe/ {
auth_basic "haha";
auth_basic_user_file /usr/local/nginx/conf/passwd;
}

用户创建

[root@linuxprobe ~]# yum -y install httpd-tools
[root@linuxprobe ~]# htpasswd -cb /usr/local/nginx/conf/passwd linuxprobe 211212
[root@linuxprobe ~]# chmod 400 /usr/local/nginx/conf/passwd
[root@linuxprobe ~]# chown nginx /usr/local/nginx/conf/passwd
[root@linuxprobe ~]# /usr/local/nginx/sbin/nginx -s reload

Nginx源码安装及调优配置Nginx源码安装及调优配置

防止DDOS攻击

通过使用limit_conn_zone进行控制单个IP或者域名的访问次数

[root@linuxprobe ~]# vim /usr/local/nginx/conf/nginx.conf

http字段中配置

limit_conn_zone $binary_remote_addr zone=addr:10m;

server的location字段配置

location / {
root html;
limit_conn addr 1;

#在其他机器上面进行并发测试
Nginx源码安装及调优配置Nginx源码安装及调优配置

[root@linuxprobe ~]# webbench -c 5000 -t 120 http://10.1.1.83/linuxprobe/index.html

#webbench安装请参考http://blog.sina.com.cn/s/blog_87113ac20102wag5.html

#nginx匹配符介绍

=    开头表示精确匹配
^~   开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。
~    开头表示区分大小写的正则匹配
~*   开头表示不区分大小写的正则匹配
!~和!~*  分别为区分大小写不匹配及不区分大小写不匹配的正则
/    通用匹配,任何请求都会匹配到。
多个location配置的情况下匹配顺序为(参考资料而来,还未实际验证,试试就知道了,不必拘泥,仅供参考):
首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求。

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
自签SSL证书配置Nginx代理Vue+SpringBoot前后端分离服务
自签SSL证书配置Nginx代理Vue+SpringBoot前后端分离服务
46 0
重识Nginx - 03 Nginx配置语法
重识Nginx - 03 Nginx配置语法
11 0
Nginx配置80端口用于多个域名
Nginx配置80端口用于多个域名
30 0
Nginx给官网配置ssl证书(https)
Nginx给官网配置ssl证书(https)
30 0
亲妈级Nginx安装教程&&核心配置讲解( 最新版 ),一步到位
亲妈级Nginx安装教程&&核心配置讲解( 最新版 ),nginx如何安装以及安装之后如何配置, 以及配置文件中的各个参数的作用,一步到位
32 0
Nginx 在Windows下配置证书
1、从证书出售商获取证书文件,并复制到nginx的conf目录下2、打开nginx.conf配置文件,写入以下代码。
23 0
cobaltstrike配置nginx反向代理
cobaltstrike配置nginx反向代理
36 0
还在手动配置Nginx?太LOW了,这个超强大的 Nginx 可视化管理工具太牛逼了!
还在手动配置Nginx?太LOW了,这个超强大的 Nginx 可视化管理工具太牛逼了!
135 0
Nginx 可视化神器!复杂配置一键生成,监控管理一条龙!
Nginx 可视化神器!复杂配置一键生成,监控管理一条龙!
51 0
+关注
shaonbean
To grow and to help others grow. To live and to help others live DevOps is everything!
文章
问答
视频
文章排行榜
最热
最新
相关电子书
更多
CentOS Nginx PHP JAVA多语言镜像使用手册
立即下载
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载