linux Nginx部署和配置

一. Nginx的部署

tips:此文档适用于linux centos6或者centos7

1. Nginx介绍

  • Nginx(“engine x”)是⼀款是由俄罗斯的程序设计师Igor Sysoev所开发⾼性能的 Web和 反向代理 服务器,也是⼀个 IMAP/POP3/SMTP 代理服务器。
  • 轻量级的web服务器
  • 延伸版本tengine(淘宝)、openresrt(章亦春)等
  • http://nginx.org 官⽹
  • http://www.nginx.cn/doc/index.html 中⽂⽂档

2. 安装依赖工具

[root@localhost ~]# yum -y install make zlib zlib-devel gcc-c++ libtool  openssl openssl-devel

3. 安装PCRE

# PCRE 作用是让 Nginx 支持 Rewrite 功能。
[root@localhost ~]# cd /usr/local/src/
[root@localhost src]# wget http://downloads.sourceforge.net/project/pcre/pcre/8.35/pcre-8.35.tar.gz
[root@localhost src]# tar zxvf pcre-8.35.tar.gz
[root@localhost src]# cd pcre-8.35
[root@localhost pcre-8.35]# ./configure
[root@localhost pcre-8.35]# make && make install
[root@localhost pcre-8.35]# pcre-config --version        #查看PCRE版本

4. 安装Nginx

[root@localhost ~]# cd /usr/local/src/
[root@localhost src]# wget https://nginx.org/download/nginx-1.16.1.tar.gz
[root@localhost src]# tar -zxvf nginx-1.16.1.tar.gz
[root@localhost src]# cd nginx-1.16.1/
[root@localhost nginx-1.16.1]# ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.35
[root@localhost nginx-1.16.1]# make && make install
[root@localhost nginx-1.16.1]# /usr/local/nginx/sbin/nginx -v  #查看Nginx版本

二. Nginx的配置

1. Nginx的常用命令

/usr/local/nginx/sbin/nginx -t    #检查配置文件的准确性
/usr/local/nginx/sbin/nginx -g /usr/local/nginx/conf/nginx.conf 检查配置文件
/usr/local/nginx/sbin/nginx     #启动Nginx
killall -s HUP nginx        #重新加载Nginx配置

2. Nginx的主配置文件详解

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服务器设置
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"';
    #$remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;
    #$remote_user:用来记录客户端用户名称;
    #$time_local: 用来记录访问时间与时区;
    #$request: 用来记录请求的url与http协议;
    #$status: 用来记录请求状态;成功是200,
    #$body_bytes_sent :记录发送给客户端文件主体内容大小;
    #$http_referer:用来记录从那个页面链接访问过来的;
    #$http_user_agent:记录客户浏览器的相关信息;

    #全局访问日志路径 
    #access_log  logs/access.log  main;
    #sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为on。如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统uptime。
    sendfile        on;
    
    #此选项允许或禁止使用socke的TCP_CORK的选项,此选项仅在使用sendfile的时候使用
    #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;

        #定义web根路径
        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;
        }

        #定义反向代理服务器 数据服务器是lamp模型
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ .php$ {
        #    proxy_pass   http://127.0.0.1;
        #}


        #定义PHP为本机服务的模型  
        # 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
        #
        #拒绝apache DR目录及子目录下的.htaccess文件访问
        #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的配置方案
    # 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;
    #    }
    #}

}

3. Nginx默认网站配置功能介绍

当Nginx配置 件中有且只有 个Server的时候,该Server就被Nginx认为是默认 站,所有发给Nginx服务 80端 的数据都会默认给该Server.

server {
    listen 80;
    server_name localhost; location / {
        root html;
        index index.html index.htm; }
    error_page 500 502 503 504 /50x.html; location = /50x.html {
        root html; }

     #以下配置的作用是限制Nginx 录访问权限。
    location /a {       
	allow 192.168.31.0/24;
	deny all;
	#return 404;
	#return http://www.jd.com; }  #return 不要开启,因为开启实际测试效果是allow的也会被return。

     #以下配置的作用是设置web认证登录
    location /b {       
	auth_basic ”登陆验证";    #语法: auth_basic string | off; 默认值: auth_basic off;
	auth_basic_user_file /etc/nginx/htpasswd; }     
  
    #以下配置是自定义的json日志格式
    log_format main_json '{'            
	'"@timestamp":"$time_local",' 
	'"client_ip": "$remote_addr",'
	'"request": "$request",'
	'"status": "$status",'
	'"bytes": "$body_bytes_sent",'
	'"x_forwarded": "$http_x_forwarded_for",'
	'"referer": "$http_referer"'
	'}';
    access_log logs/access_json.log main_json; 

    #以下配置是防盗链配置
    location /images/ {	#防盗链精确目录匹配
	alias /data/images/;
	valid_referers none blocked *.baidu.com; 
		if ($invalid_referer) {
		return 403;
		}
	}

    location ~* .(png|bmp|jpg) {	#防盗链宽匹配
	alias /data/images/;
	valid_referers none blocked *.baidu.com; 
		if ($invalid_referer) {
		return 403;
		}
	}
    
}
#设备web登录需要使用到的账号和密码信息
[root@localhost ~]# yum -y install httpd-tools #安装httpd工具,为后续准备
[root@localhost ~]# mkdir /etc/nginx
[root@localhost nginx]# htpasswd -c /etc/nginx/htpasswd test1        #创建文件并增加第一个用户
New password:
Re-type new password:
Adding password for user test1
[root@localhost nginx]# htpasswd -m /etc/nginx/htpasswd test2       #增加第二个用户
New password:
Re-type new password:
Adding password for user test2
[root@localhost nginx]#
#nginx日志管理
    # Nginx访问日志志主要有两个参数控制
        # 1) log_format # 来定义记录日志的格式(可以定义多种日志格式,取不同名字即可)
        # log_format log_name string
        # 2) access_log # 来指定日志文件的路径及使用的何种日志格式记录日志
        # access_log logs/access.log main;
    # log_format格式变量:
	# $remote_addr #记录访问网站的客户端地址
	# $remote_user #远程客户端用户名
	# $time_local #记录访问时间与时区
	# $request # 用户的http请求起始行信息
	# $status #http状态码,记录请求返回的状态码, 如:200、301、404等
	# $body_bytes_sent #服务器发送给客户端的响应body字节数
	# $http_referer #记录此次请求是从哪个连接访问过来的,可以根据该参数进行防盗链设置。
	# $http_user_agent #记录客户端访问信息, 例如:浏览器、手机客户端等
	# $http_x_forwarded_for #当前端有代理服务器时,设置web节点记录客户端地址的配置,此参数生效的前提是代理服务器也要进行相关的x_forwarded_for设置

4. Nginx虚拟主机介绍

⼀个web服务器软件如何发布多个web网站,就叫做虚拟主机,就是把⼀台物理服务器划分成多个“虚拟”的服务器,每⼀个虚拟主机都可以有独⽴的域名和独⽴的⽬录。

#基于IP的虚拟主机
server {
	listen 192.168.31.42:80;
	location / {
	root html/abc;
	index index.html index.htm index.php;
	}
}
server {
	listen 192.168.31.52:80;
	location / {
	root html/cbd;
	index index.html index.htm;
	}
}
#基于端口的虚拟主机
server {
	listen 80;
	server_name www.abc.com;
	location / {
	root html/abc;
	index index.html index.htm index.php;
	}
}
server {
	listen 8080;
	server_name www.abc.com;
	location / {
	root html/cbd;
	index index.html index.htm;
	}
}
#基于域名的虚拟主机
server {
	listen 80;
	server_name www.abc.com;
	location / {
	root html/abc;
	index index.html index.htm index.php;
	}
}
server {
	listen 80;
	server_name www.cbd.com;
	location / {
	root html/cbd;
	index index.html index.htm;
	}
}

5. Nginx的反向代理

# 总结:反向代理是发布服务器站点使用的,正向代理是代理用户上网用的。
# 反向代理的应用场景
    # 堡垒机场景
    # 内⽹服务器发布场景
    # 缓存场景
location / {
proxy_pass http://mysvr ;#请求转向mysvr 定义的服务器列表
proxy_set_header Host $host;	#增加请求头有如下两种
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m; #允许客户端请求的最⼤单⽂件字节数
client_body_buffer_size 128k; #缓冲区代理缓冲⽤户端请求的最⼤字节数,
proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size 4k; #设置代理服务器(nginx)保存⽤户头信息的缓冲区⼤⼩
proxy_buffers 4 32k; #proxy_buffers缓冲区,⽹⻚平均在32k以下的话,这样设置
proxy_busy_buffers_size 64k; #⾼负荷下缓冲⼤⼩(proxy_buffers*2)
proxy_temp_file_write_size 64k; #设定缓存⽂件夹⼤⼩,⼤于这个值,将从upstream服务器传
}

6. Nginx限速

#限速介绍
限速该特性可以限制某个⽤户在⼀个给定时间段内能够产⽣的HTTP请求数。请求可以简单到就是⼀个对于主⻚的GET请求或者⼀个登陆表格的POST请求。
限速也可以⽤于安全⽬的上,⽐如暴⼒密码破解攻击。通过限制进来的请求速率,并且(结合⽇志)标记出⽬标URLs来帮助防范DDoS攻击。⼀般地说,限流是⽤在
保护上游应⽤服务器不被在同⼀时刻的⼤量⽤户请求湮没。
#限速应用场景
DDOS防御
下载场景保护IO
#限速原理
⽔(请求)从上⽅倒⼊⽔桶,从⽔桶下⽅流出(被处理);
来不及流出的⽔存在⽔桶中(缓冲),以固定速率流出;
⽔桶满后⽔溢出(丢弃)。
这个算法的核⼼是:缓存请求、匀速处理、多余的请求直接丢弃。
# Nginx限速的实现
Nginx官⽅版本限制IP的连接和并发分别有两个模块:
limit_req_zone ⽤来限制单位时间内的请求数,即速率限制。
limit_req_conn ⽤来限制同⼀时间连接数,即并发限制。
# 限速案例一
#基于IP对下载速率做限制 限制每秒处理1次请求,对突发超过5个以后的请求放⼊缓存区
http {
 limit_req_zone $binary_remote_addr zone=jet:10m rate=1r/s;
 server {
 location /search/ {
 limit_req zone=jet burst=5 nodelay;
 }
}
limit_req_zone $binary_remote_addr zone=jet:10m rate=1r/s;
第⼀个参数:$binary_remote_addr 表示通过remote_addr这个标识来做限制,
“binary_”的⽬的是缩写内存占⽤量,是限制同⼀客户端ip地址。
第⼆个参数:zone=jet:10m表示⽣成⼀个⼤⼩为10M,名字为one的内存区域,⽤来存储访问的频次信息。
第三个参数:rate=1r/s表示允许相同标识的客户端的访问频次,这⾥限制的是每秒1次,还可以有⽐如30r/m的。
limit_req zone=jet burst=5 nodelay;
第⼀个参数:zone=baism 设置使⽤哪个配置区域来做限制,与上⾯limit_req_zone ⾥的name对应。
第⼆个参数:burst=5,重点说明⼀下这个配置,burst爆发的意思,这个配置的意思是设置⼀个⼤⼩为5的缓冲区当有⼤量请求(爆发)过来时,超过了访问频次限制的请
求可以先放到这个缓冲区内。
第三个参数:nodelay,如果设置,超过访问频次⽽且缓冲区也满了的时候就会直接返回503,如果没有设置,则所有请求会等待排队。
# 限速案例二
#基于IP做连接限制 限制同⼀IP并发为1 下载速度为100K
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
 listen 80;
 server_name localhost;
 location / {
 root html;
 index index.html index.htm;
 }
 location /abc {
 limit_conn addr 1;
 limit_rate 100k;
 }
 }

7. Nginx的URL重写

1)URL重写介绍

  • rewrite模块(ngx_http_rewrite_module)。
  • Rewrite功功能是Nginx服务器提供的⼀个重要功能。⼏乎是所有的web产品必备技能,⽤于实现URL重写。URL重写是⾮常有⽤的功能,⽐如它可以在我们在改变⽹站结构后,不需要客户端修改原来的书签,也不需要其他⽹站修改对我们⽹站的友情链接,还可以在⼀定程度上提⾼⽹站的安全性,能够让我们的⽹站显得更专业。
  • Nginx服务器Rewrite功能的实现是依赖于PCRE(Perl Compatible Regular Expression。Perl兼容的正则表达式)的⽀持,所以在编译安装Nginx之前,需要安装PCRE库。

2)应用场景

  • 域名变更
  • ⽤户跳转 (从某个连接跳到另⼀个连接)
  • 伪静态场景 (便于CDN缓存动态⻚⾯数据)

3)URL重写实现

#URL模块语法
set 设置变量
if 负责语句中的判断
return 返回返回值或URL
break 终⽌后续的rewrite规则
rewrite 重定向URL
# set指令 ⾃定义变量
# Syntax:
# set $variable value;
# Default:
# —
# Context:
# server, location, if
#举例:将http://192.168.31.17 重写为 http://192.168.31.17/jet
location / {
     set $name jet;
     rewrite ^(.*)$ http://192.168.31.17/$name;
 }
# if 指令 负责判断
# Syntax:
# if (condition) { ... }
# Default:
# —
# Context:
# server, location

# return 指令 定义返回数据
# Syntax: return code [text];
# return code URL;
# return URL;
# Default: —
# Context: server, location, if

# 举例,如果用户是通过谷歌浏览器访问的返回403:
location / {
     root html;
     index index.html index.htm;
     if ($http_user_agent ~* 'Chrome') {
     return 403;
     }
}
# break 指令 停⽌执⾏当前虚拟主机的后续rewrite指令集
# Syntax: break;
# Default:—
# Context:server, location, if
location / {
     root html;
     index index.html index.htm;
     if ($http_user_agent ~* 'Chrome') {
         break;
         return 403;
     }
 }
# URL rewrite 语法
 rewrite <regex> <replacement> [flag];
关键字 正则 替代内容 flag标记
flag:
last #本条规则匹配完成后,继续向下匹配新的location URI规则
break #本条规则匹配完成即终⽌,不再匹配后⾯的任何规则
redirect #返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent #返回301永久重定向,浏览器地址栏会显示跳转后的URL地址

# URL rewrite 举例
www.abc.com 重写为 www.def.com
server {
     listen 80;
     server_name www.abc.com;
     location / {
     rewrite ^/$ http://www.def.com permanent ;
     }
}
# 注意:重定向就是将⽹⻚⾃动转向重定向
# 301永久性重定向:新⽹址完全继承旧⽹址,旧⽹址的排名等完全清零
# 301重定向是⽹⻚更改地址后对搜索引擎友好的最好⽅法,只要不是暂时搬移的情况,都建议使⽤301来做转址。
# 302临时性重定向:对旧⽹址没有影响,但新⽹址不会有排名,搜索引擎会抓取新的内容⽽保留旧的⽹址
# break 本条规则匹配完成即终⽌,不再匹配后⾯的任何规则,实际效果类似临时重定向,返回客户端302
根据⽤户浏览器重写访问⽬录
如果是chrome浏览器 就将 http://192.168.10.42/$URI 重写为 http://192.168.10.42/chrome/$URI
location / {
    if ($http_user_agent ~* 'chrome'){
        rewrite ^(.*)$ /chrome/$1 last;
     }
     location /chrome {
         root html ;
         index index.html;
     }
}
 #^ 以什么开头 ^a
 #$ 以什么结尾 c$
 #. 除了回⻋以外的任意⼀个字符
 #* 前⾯的字符可以出现多次或者不出现
 #更多内容看正则表达式 re
原文地址:https://www.cnblogs.com/wangzengyi/p/12630267.html