Nginx

Nginx

Nginx是一款轻量级的Web服务器,反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少,并发能力强。

apache 相对于nginx 的优点:rewrite ,比nginx 的rewrite 强大,模块超多,基本想到的都可以找到 少bug ,nginx 的bug 相对较多 超稳定。存在就是理由,一般来说,需要性能的web 服务,用nginx。如果不需要性能只求稳定,那就apache。


在这里插入图片描述

Nginx的安装

1、安装依赖包

yum -y install pcre-devel zlib-devel gcc gcc-c++ make

2、创建运行用户

useradd -M -s /sbin/nologin nginx

3、编译安装

cd /opt
tar zxvf nginx-1.12.0.tar.gz -C /opt/

cd nginx-1.12.0/
./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module

make && make install

4、优化路径

ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/

5、添加 Nginx 系统服务

vim /lib/systemd/system/nginx.service
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target

chmod 754 /lib/systemd/system/nginx.service
systemctl start nginx.service
systemctl enable nginx.service

Nginx主配置文件

nginx.conf配置文件中有三大块:全局块,events块,http块

http中可以配置多个server块,每个server块又可以配置多个location块

vim /usr/local/nginx/conf/nginx.conf

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

}

全局块

user:用于配置运行Nginx服务器的worker进程的用户和用户组

worker_processes:配置Nginx生成工作进程的数量, 理论上来说,worker process的值越大,处理的并发量越高。但建议该值与系统cpu的个数保持一致。配置使用这个时,master_process应该设为off(数量也可设置为内核数)

include:用来引入其他配置文件,使nginxde 配置更加灵活,可以在nginx.conf文件中任何位置进行配置

events块

worker connections:用来配置单个worker进程最大的连接数

http块

gzip on:开启网页压缩

keepalive_timeout:跟时间表示,一段时间内保持打开状态

server块和location块
server {  
    listen       80;     #默认监听窗口
    server_name  localhost;  #域名

    #access_log  /var/log/nginx/host.access.log  main;

    location / {         
        root   /usr/share/nginx/html;     #资源所对应的目录,index.html..要放在此目录下
        index  index.html index.htm;
    }
 	error_page   500 502 503 504  /50x.html;  #发生指定状态码时跳转到50x.html
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Nginx优化配置

隐藏版本号
方法一:修改配置文件方式
vim /usr/local/nginx/conf/nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
    server_tokens off;								#添加,关闭版本号
    ......
}

systemctl restart nginx
curl -I http://192.168.237.138						#验证
方法二:修改源码文件,重新编译安装
vim /opt/nginx-1.12.0/src/core/nginx.h
#define NGINX_VERSION "1.1.1" 					#修改版本号
#define NGINX_VER "IIS" NGINX_VERSION 			#修改服务器类型

cd /opt/nginx-1.12.0/
./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module
make && make install

vim /usr/local/nginx/conf/nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
    server_tokens on;
	......
}

systemctl restart nginx
curl -I http://192.168.237.138                 #验证
修改用户与组
vim /usr/local/nginx/conf/nginx.conf
user nginx nginx; 								#取消注释,修改用户为 nginx ,组为 nginx

systemctl restart nginx

ps aux | grep nginx								#验证
缓存时间

当Nginx将网页数据返回给客户端后,可设置缓存的时间,以方便在日后进行相同内容的请求时直接返回,避免重复请求,加快了访问速度,一般针对静态网页设置,对动态网页不设置缓存时间

vim /usr/local/nginx/conf/nginx.conf
http {
......
	server {
	...... 
		location / {
			root html;
			index index.html index.htm;
		}
		
		location ~ \.(gif|jpg|jepg|png|bmp|ico)$ { 		#加入新的 location,以图片作为缓存对象
			root html;
			expires 1d;									#指定缓存时间,1天
		}
......
	}
}

http://www.kgc.com/tang.jpg								#将一张tang.jpg放入存储目录
systemctl restart nginx									#重启

验证:
在Linux系统中,打开火狐浏览器,右击点查看元素
选择 网络 ---> 选择 HTML、WS、其他 
访问 http://192.168.237.138/game.jpg ,双击200响应消息查看响应头中包含 Cahce-Control:max-age=86400 表示缓存时间是 86400 秒。也就是缓存一天的时间,一天之内浏览器访问这个页面,都是用缓存中的数据,而不需要向 Nginx 服务器重新发出请求,减少了服务器的使用带宽。
日志切割
vim /opt/fenge.sh
#!/bin/bash
#Filename: fenge.sh

day=$(date -d "-1 day" "+%Y%m%d")											#显示前一天的时间
logs_path="/var/log/nginx"
pid_path="/usr/local/nginx/logs/nginx.pid"
[ -d $logs_path ] || mkdir -p $logs_path 									#创建日志文件目录
mv /usr/local/nginx/logs/access.log ${logs_path}/kgc.com-access.log-$day	#移动并重命名日志文件
kill -USR1 $(cat $pid_path)													#重建新日志文件
find $logs_path -mtime +30 -exec rm -rf {} \;								#删除30天之前的日志文件
#find $logs_path -mtime +30 | xargs rm -rf 

chmod +x /opt/fenge.sh														#赋执行权限
/opt/fenge.sh																#执行验证
ls /var/log/nginx															#查看验证
ls /usr/local/nginx/logs/access.log 										#查看验证

crontab -e																	#设置定时任务
0 1 * * * /opt/fenge.sh
连接超时
vim /usr/local/nginx/conf/nginx.conf
http {
...... 
    keepalive_timeout 65 180;									#设置保持时间,设置成0就是禁止keepalived
    client_header_timeout 80;				#客户端向服务端发送一个完整的 request header 的超时时间。如果客户端在指定时间内没有发送一个完整的 request header,Nginx 返回 HTTP 408(Request Timed Out)。
    
    client_body_timeout 80;					#指定客户端与服务端建立连接后发送 request body 的超时时间。如果客户端在指定时间内没有发送任何内容,Nginx 返回 HTTP 408(Request Timed Out)。
...... 
}

systemctl restart nginx											#重启
更改进程数
cat /proc/cpuinfo | grep -c "physical id"	#查看cpu核数
ps aux | grep nginx							#查看nginx主进程中包含几个子进程

vim /usr/local/nginx/conf/nginx.conf
worker_processes  2;				#修改为核数相同或者2倍
worker_cpu_affinity 0110;			#设置每个进程由不同cpu处理,进程数配为4时0001 0010 0100 1000

systemctl restart nginx
配置网页压缩
vim /usr/local/nginx/conf/nginx.conf
http {
...... 
   gzip on;							#取消注释,开启gzip压缩功能
   gzip_min_length 1k;      		#最小压缩文件大小
   gzip_buffers 4 64k;      		#压缩缓冲区,大小为4个64k缓冲区
   gzip_http_version 1.1;   		#压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
   gzip_comp_level 6;       		#压缩比率
   gzip_vary on;					#支持前端缓存服务器存储压缩页面
   gzip_types text/plain text/javascript application/x-javascript text/css text/xml application/xml application/xml+rss image/jpg image/jpeg image/png image/gif application/x-httpd-php application/javascript application/json;		#压缩类型,表示哪些网页文档启用压缩功能
...... 
}

cd /usr/local/nginx/html
先将game.jpg文件传到/usr/local/nginx/html目录下
vim index.html
...... 
<img src="tang.jpg"/>				#网页中插入图片
</body>
</html>

systemctl restart nginx
验证:
在Linux系统中,打开火狐浏览器,右击点查看元素
选择 网络 ---> 选择 HTML、WS、其他 
访问 http://192.168.80.10 ,双击200响应消息查看响应头中包含 Content-Encoding: gzip
配置防盗链
vim /usr/local/nginx/conf/nginx.conf
http {
......
	server {
	......
		location ~* \.(jpg|gif|swf)$ {						#~* \.(jpg|gif|swf)$ :这段正则表达式表示匹配不区分大小写,以.jpg 或.gif 或.swf 结尾的文件;
		
			valid_referers none blocked *.kgc.com kgc.com;
			#设置信任的网站,可以正常使用图片
			#允许没有http_refer的请求访问资源(根据Referer的定义,它的作用是指示一个请求是从哪里链接过来的,如果直接在浏览器			  的地址栏中输入一个资源的URL地址,那么这种请求是不会包含 Referer 字段的),如 http://www.kgc.com/tang.jpg
			#blocked:允许不是http://开头的,不带协议的请求访问资源; 
			#*.kgc.com:只允许来自指定域名的请求访问资源,如 http://www.kgc.com
			
			if ( $invalid_referer ) {
				rewrite ^/ http://www.kgc.com/error.png;
				#return 403;
            }
            #if语句:如果链接的来源域名不在valid_referers所列出的列表中,$invalid_referer为true,则执行后面的操作,即进			 行重写或返回 403 页面
        }
	......
	}
}

网页准备:
Web源主机(192.168.237.138)配置:
cd /usr/local/nginx/html
将game.jpg、error.png文件传到/usr/local/nginx/html目录下
vim index.html
...... 
<img src="game.jpg"/>
</body>
</html>

echo "192.168.237.138 www.kgc.com" >> /etc/hosts 
echo "192.168.237.12 www.benet.com" >> /etc/hosts 

盗链网站主机(192.168.237.12):
cd /usr/local/nginx/html
vim index.html
...... 
<img src="http://www.kgc.com/game.jpg"/>
</body>
</html>

echo "192.168.237.138 www.kgc.com" >> /etc/hosts 
echo "192.168.237.12 www.benet.com" >> /etc/hosts 

在盗图网站主机上进行浏览器验证
http://www.benet.com
fpm参数优化
Nginx的PHP解析功能实现如果是交由FPM处理的,为了提高PHP的处理速度,可对FPM模块进行参数的调整
根据服务器的内存与服务负载,调整FPM模块参数

vim /usr/local/php/etc/php-fpm.conf 
pid = run/php-fpm.pid

vim /usr/local/php/etc/php-fpm.d/www.conf
--96行--
pm = dynamic				#fpm进程启动方式,动态的
--107行--
pm.max_children=20			#fpm进程启动的最大进程数
--112行--
pm.start_servers = 5		#动态方式下启动时默认开启的进程数,在最小和最大之间
--117行--
pm.min_spare_servers = 2	#动态方式下最小空闲进程数
--122行--
pm.max_spare_servers = 8	#动态方式下最大空闲进程数


kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`			#重启php-fpm
netstat -anpt | grep 9000

location和rewrite

从功能看 rewrite 和 location 似乎有点像,都能实现跳转,主要区别在于 rewrite 是在同一域名内更改获取资源的路径,而 location 是对一类路径做控制访问或反向代理,还可以proxy_pass 到其他机器

rewrite 对访问的域名或者域名内的URL路径地址重写
location 对访问的路径做访问控制或者代理转发

常用的Nginx 正则表达式:

符号说明
^匹配输入字符串的起始位置
$匹配输入字符串的结束位置
*匹配前面的字符零次或多次。如“ol*”能匹配“o”及“ol”、“oll”
+匹配前面的字符一次或多次。如“ol+”能匹配“ol”及“oll”、“olll”,但不能匹配“o”
匹配前面的字符零次或一次,例如“do(es)?”能匹配“do”或者“does”,”?”等效于”{0,1}”
.匹配除“\n”之外的任何单个字符,若要匹配包括“\n”在内的任意字符,请使用诸如“[.\n]”之类的模式
\将后面接着的字符标记为一个特殊字符或一个原义字符或一个向后引用。如“\n”匹配一个换行符,而“$”则匹配“$”
\d匹配纯数字[0-9] \s :空白符 \w :任意单词字符包括下划线[A-Za-z0-9_]
{n}重复 n 次
{n,}重复 n 次或更多次
{n,m}重复 n 到 m 次
[]定义匹配的字符范围
[c]匹配单个字符 c
[a-z]匹配 a-z 小写字母的任意一个
[a-zA-Z0-9]匹配所有大小写字母或数字
()表达式的开始和结束位置
|或运算符

location 大致可以分为三类:
精准匹配:location = / {…}
一般匹配:location / {…}
正则匹配:location ~ / {…}

匹配规则说明
=进行普通字符精确匹配,也就是完全匹配
^~表示普通字符匹配,使用前缀匹配。如果匹配成功,则不再匹配其它 location
~区分大小写的匹配
~*不区分大小写的匹配
!~区分大小写的匹配取非
!~*不区分大小写的匹配取非

location 匹配

首先看 优先级:精确= > 前缀^~ > 正则~,~* > 一般 > 通用/
优先级相同:正则看上下顺序,上面的优先;一般匹配看长度,最长匹配的优先
精确、前缀、正则、一般 都没有匹配到,最后再看通用匹配

实际网站使用中,至少有三个匹配规则定义:
第一个必选规则
直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,比如说官网。
可以是一个静态首页,也可以直接转发给后端应用服务器

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

第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项
有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用

location ^~ /static/ {
    root /webroot/static/;
}

location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}

第三个规则就是通用规则,比如用来转发带.php、.jsp后缀的动态请求到后端应用服务器
非静态文件请求就默认是动态请求

location / {
    proxy_pass http://tomcat_server;
}

rewrite功能就是,使用nginx提供的全局变量或自己设置的变量,结合正则表达式和标记位实现URL重写以及重定向,比如:更换域名后需要保持旧的域名能跳转到新的域名上、某网页发生改变需要跳转到新的页面、网站防盗链等等需求,rewrite只能放在server{},location{},if{}中,并且默认只能对域名后边的除去传递的参数外的字符串起作用

rewrite跳转实现:
Nginx:通过ngx_http_rewrite_module 模块支持URL重写、支持if条件判断,但不支持else
跳转:从一个 location跳转到另一个location,循环最多可以执行10次,超过后nginx将返回500错误
PCRE支持:perl兼容正则表达式的语法规则匹配
重写模块 set 指令:创建新的变量并设其值

rewrite 执行顺序如下:
(1) 执行 server 块里面的 rewrite 指令
(2) 执行 location 匹配
(3) 执行选定的 location 中的 rewrite 指令

语法格式:rewrite <regex> <replacement> [flag];
regex:表示正则匹配规则
replacement:表示跳转后的内容
flag:表示rewrite支持的flag标记
flag标记说明
last本条规则匹配完成后,不终止重写后的url匹配,一般用在 server 和 if 中
break本条规则匹配完成即终止,终止重写后的url匹配,一般使用在 location 中
redirect返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent返回301永久重定向,浏览器地址栏会显示跳转后的URL地址
基于域名的跳转
vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.kgc.com;		#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.kgc.com-access.log;		#日志修改
	location / {
	#添加域名重定向
        if ($host = 'www.kgc.com'){						#$host为rewrite全局变量,代表请求主机头字段或主机名
			rewrite ^/(.*)$ http://www.benet.com/$1 permanent;	#$1为正则匹配的内容,即“域名/”之后的字符串
        }
        root   html;
        index  index.html index.htm;
    }
}

echo "192.168.237.138 www.kgc.com www.benet.com" >> /etc/hosts
systemctl restart nginx
浏览器输入模拟访问 http://www.kgc.com/test/1.html(虽然这个请求内容是不存在的)
会跳转到www.benet.com/test/1.html,查看元素可以看到返回301,实现了永久重定向跳转,而且域名后的参数也正常跳转
基于客户端 IP 访问跳转
vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.kgc.com;		#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.kgc.com-access.log;		#日志修改

	#设置是否合法的IP标记
    set $rewrite true;							#设置变量$rewrite,变量值为boole值true
    #判断是否为合法IP
	if ($remote_addr = "192.168.237.138"){		#当客户端IP为192.168.237.138时,将变量值设为false,不进行重写
        set $rewrite false;
    }
	#除了合法IP,其它都是非法IP,进行重写跳转维护页面
    if ($rewrite = true){						#当变量值为true时,进行重写
        rewrite (.+) /weihu.html;				#将域名后边的路径重写成/weihu.html,例如www.kgc.com/weihu.html
    }
    location = /weihu.html {
        root /var/www/html;						#网页返回/var/www/html/weihu.html的内容
    }
	
	location / {
        root   html;
        index  index.html index.htm;
    }
}


mkdir -p /var/www/html/
echo "<h1>We are maintaining now!</h1>" > /var/www/html/weihu.html
systemctl restart nginx
只有 IP 为 192.168.237.138 能正常访问,其它地址都是维护页面
基于旧域名跳转到新域名后面加目录
vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  bbs.kgc.com;		#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.kgc.com-access.log;
	#添加
	location /post {
        rewrite (.+) http://www.kgc.com/bbs$1 permanent;		#这里的$1为位置变量,代表/post
    }
	
	location / {
        root   html;
        index  index.html index.htm;
    }
}


mkdir -p /usr/local/nginx/html/bbs/post
echo "this is 1.html"  >> /usr/local/nginx/html/bbs/post/1.html
echo "192.168.237.138 bbs.kgc.com"  >> /etc/hosts
systemctl restart nginx
使用浏览器访问 http://bbs.kgc.com/post/1.html 跳转到 http://www.kgc.com/bbs/post/1.html
基于参数匹配的跳转
vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.kgc.com;		#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.kgc.com-access.log;
	
	if ($request_uri ~ ^/100-(100|200)-(\d+).html$) {
	    rewrite (.+) http://www.kgc.com permanent;
	}
	
	location / {
	    root   html;
	    index  index.html index.htm;
	}

}

systemctl restart nginx
使用浏览器访问 http://www.kgc.com/100-200-100.html 或 http://www.kgc.com/100-100-100.html 跳转到http://www.kgc.com页面
基于目录下所有 php 结尾的文件跳转
vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.kgc.com;		#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.kgc.com-access.log;
	
	location ~* /upload/.*\.php$ {
        rewrite (.+) http://www.kgc.com permanent;
    }

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

systemctl restart nginx
浏览器访问 http://www.kgc.com/upload/123.php 跳转到http://www.kgc.com页面
基于最普通一条 url 请求的跳转
vim /usr/local/nginx/conf/nginx.conf
server {
	listen       80;
	server_name  www.kgc.com;		#域名修改	
	charset utf-8;
	access_log  /var/log/nginx/www.kgc.com-access.log;
	
    location ~* ^/abc/123.html {
        rewrite (.+) http://www.kgc.com permanent;
    }

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

systemctl restart nginx
浏览器访问 http://www.kgc.com/abc/123.html 跳转到http://www.kgc.com页面
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值