运维学习-centos7上配置nginx基础配置

    nginx是linux上常用的web服务器,功能能多。一般采用编译安装,测试使用的版本是nginx1.15.7 http://nginx.org/

一、编译安装nginx

安装Nginx所需的pcre库。pcre全称是perl compatible regular expressions,中文名称为perl兼容正则表达式,目的是使nginx支持具备URI重写功能的rewrite模块。

yum安装即可

yum install pcre pcre-devel -y

安装openssl ,openssl-devel 和gcc

openssl使使用https服务时候使用的模块,如果不安装则会再nginx安装过程中会报错

gcc GCC(GNU Compiler Collection,GNU编译器套件),即编译器

yum install openssl openssl-devel gcc -y

安装ngnix

wget  
useradd nginx -s /sbin/nologin -M
tar xvf nginx-1.15.7.tar.gz
cd nginx-1.15.7
./configure --usr=nginx --group=nginx --prefix/application/nginx-1.15.7/ --with-http_stub_status_module --with-http_ssl_module  #添加基础模块
make 
make install
ln -s /application/nginx-1.15.7/ /application/nginx            #更改为/application/nginx,工程经验

完成安装后启动并检查nginx状态

/application/nginx/sbin/nginx        #启动nginx
lsof -i:80                           #检查端口

image.png

如果能通过网页url访问 则说明nginx安装成功


二、nginx功能模块说明


Nginx http 功能模块模块说明
ngx_http_core_module包括一些核心的 http 参数配置,对应 Nginx 的配置为 HTTP 区块部分
ngx_http_access_module访问控制模块,用来控制网站用户对 Nginx 的访问
ngx_http_gzip_module压缩模块,对 Nginx 返回的数据压缩,属于性能优化模块
ngx_http_fastcgi_moduleFastCGI 模块,和动态应用相关的模块,如 PHP
ngx_http_proxy_moduleproxy 代理模块
ngx_http_upstream_module负载均衡模块,可实现网站的负载均衡和节点的健康检查
ngx_http_rewrite_moduleURL 地址重写模块
ngx_http_limit_conn_module限制用户并发连接数以及请求数的模块
ngx_http_limit_req_module根据定义的 key 限制 Nginx 请求过程的速率
ngx_http_log_module访问日志模块,以指定的格式记录 Nginx 客户访问日志等信息
ngx_http_auth_basic_moduleWeb 认证模块,设置 Web 用户通过账号密码访问 Nginx
ngx_http_ssl_modulessl 模块,用于加密的 http 连接,如 https
ngx_http_stub_status_module记录 Nginx 基本访问状态信息等的模块

nginx目录结构说明

[root@www ~]# tree /application/nginx/
/application/nginx/
|-- client_body_temp
|-- conf                                  #这是Nginx所有配置文件的目录,极其重要
|   |-- fastcgi.conf                    #fastcgi相关参数的配置文件
|   |-- fastcgi.conf.default                 #fastcgi.conf的原始备份
|   |-- fastcgi_params                   #fastcgi的参数文件
|   |-- fastcgi_params.default
|   |-- koi-utf
|   |-- koi-win
|   |-- mime.types                      #媒体类型,
|   |-- mime.types.default
|   |-- nginx.conf                      #这是Nginx默认的主配置文件
|   |-- nginx.conf.default
|   |-- scgi_params                     #scgi相关参数文件,一般用不到
|   |-- scgi_params.default
|   |-- uwsgi_params                       #uwsgi相关参数文件,一般用不到
|   |-- uwsgi_params.default
|   `-- win-utf
|-- fastcgi_temp                       #fastcgi临时数据目录
|-- html                       #这是编译安装时Nginx的默认站点目录,类似
                    Apache的默认站点htdocs目录
|   |--50x.html     #     错误页面优雅替代显示文件,例如:出现502错误时会调用此页面
         #     error_page   500502503504  /50x.html;
|   `-- index.html   #     默认的首页文件,首页文件名字是在nginx.conf中事先定义好的。
|-- logs          #这是Nginx默认的日志路径,包括错误日志及访问日志
|   |-- access.log      #     这是Nginx的默认访问日志文件,使用tail -f access.log,可以实时观看网站用户访问情况信息
|   |-- error.log      #     这是Nginx的错误日志文件,如果Nginx出现启动故障等问题,一定要看看这个错误日志
|   `-- nginx.pid      #     Nginx的pid文件,Nginx进程启动后,会把所有进程的ID号写到此文件
|-- proxy_temp       #临时目录
|-- sbin      #这是Nginx命令的目录,如Nginx的启动命令nginx
|   `-- nginx      #Nginx的启动命令nginx
|-- scgi_temp      #临时目录
`-- uwsgi_temp      #临时目录
9 directories,21 files


nginx的主配置文件说明

...              #全局块

events {         #events块
   ...
}

http      #http块
{
    ...   #http全局块
    server        #server块
    { 
        ...       #server全局块
        location [PATTERN]   #location块
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局块
}


三、nginx简单运用

3.1多域名虚拟主机

基于域名的虚拟主机,前提使已经搭建好了域名服务器,www.chucloud.com和web.chucloud.com解析为nginx的服务器地址

修改nginx.conf文件

server{
    listen 80;
    server_name www.chucloud.com; #绑定域名
    root html/www; #网站根目录
    index index.htm index.html ; #默认文件
}
 
server{
    listen 80;
    server_name bbs.chucloud.com; #绑定域名
    root html/bbs; #网站根目录
    index index.htm index.html ; #默认文件
    
}

创建新增域名分别对饮的站点目录及文件

mkdir ../html/www ../html/blog -p
echo " > ../html/www/index.html
echo " > ../html/bbs/index.html

检查nginx语法及重新加载

/application/nginx/sbin/nginx -t
/application/nginx/sbin/nginx -s reload

image.png

3.2多端口虚拟机主机

修改配置文件

server{
    listen 80;        
    server_name www.chucloud.com; #绑定域名
    root html/www; #网站根目录
    index index.htm index.html ; #默认文件
}
 
server{
    listen 81;                    #修改端口
    server_name bbs.chucloud.com; #绑定域名
    root html/bbs; #网站根目录
    index index.htm index.html ; #默认文件
    
}

端口任意修改,只要不和已有服务冲突即可

检查nginx语法及重新加载

/application/nginx/sbin/nginx -t
/application/nginx/sbin/nginx -s reload

image.png

3.3 优化配置文件

nginx的主配置文件为nginx.conf,主配置文件包含的所有虚拟主机子配置文件会统一放入extra目录中,虚拟主机的配置文件按照网站的域名或者功能取名,例如www.conf bbs.conf blog,conf等。

使用参数include,语法如下

include file |mask;

修改完成的include配置的主配置文件如下

worker_processes  1;
error_log    logs/error.log;
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_usr_agent" "$http_x_forwarded_for"';
    sendfile        on;
    keepalive_timeout  65;
include       extra/www.conf;            #定义额外配置路径,绝对路径为/application/nginx/conf/extra
include       extra/bbs.conf;
include       extra/blog.conf;
include       extra/status.conf;
}

单个虚拟机主机配置文件,blog.conf如下所示:

server {
        listen       81;
        server_name  blog.chucloud.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }

完成配置后,检查nginx语法,重启nginx生效

image.png


3.4配置nginx status

nginx软件功能模块中有一个ngx_stub_status_module模块,该模块主要功能是记录nginx的基本访问信息,可以了解nginx的工作状态,例如使用信息等。在编译Nginx 时必须增加http_stub_status_module模块来支持

在 extra路径下新建status.conf 文件,配置如下

#status
server{
    listen 80;
    server_name status.chucloud.com;
    location / {
        stub_status on;                #打开状态信息开关
        access_log off;
      }
   }

检查语句并重启nginx后,访问status.chucloud.com

image.png

说明:

1、server 表示目前处理了38个连接

2、accepts表示目前创建了38次握手

3、handled requests表示处理了60次请求

4、reading为nginx读取到客户端的Header信息数

5、writing为nginx返回给客户端的Header信息数

6、waiting为nginx已处理完正在等候下一次请求指令的驻留连接


3.5 为nginx增加错误日志(error_log)配置

nginx会把自身运行的故障信息及用户访问的日志信息记录到制定日志文件

参数名字为error_log,可以放在main区块中全局配置,也可以放置在不同的虚拟机中单独记录。

语法格式如下:

error_log                file                       level;

关键字                    日志文件               错误日志级别

其中关键字error_log不能改变,日志文件可以制定任意存放日志的目录、错误日志级别常见有[debug|info|notice|warn|error|crit|alert|emerg]

默认值为:

#default: error_log logs/error.log error;

在主配置文件nginx.conf中,错误日志配置如下:

image.png


3.6访问日志

    nginx软件会把每个用户访问网站的日志信息记录到制定的日志文件中,提供给网站分析用户浏览行为,此功能由ngx_http_log_module模块负责

参数如下

log_format        用来定义日志的格式

access_log        用来指定日志路径以及何种日志记录

日志格式中默认如下:

 log_format main '$remote_addr - $remote_user [$time_local] "$request"'
                    '$status $body_bytes_sent "$http_referer"'
                    '$http_usr_agent" "$http_x_forwarded_for"';

记录日志默认参数如下

access_log         logs/access.log      main;

日志变量说明

1.$remote_addr 与$http_x_forwarded_for 用以记录客户端的ip地址; 
2.$remote_user :用来记录客户端用户名称; 
3.$time_local : 用来记录访问时间与时区; 
4.$request : 用来记录请求的url与http协议; 
5.$status : 用来记录请求状态;成功是200, 
6.$body_bytes_sent:发送给客户端的文件主体内容的大小,比如899,可以将日志每条记录中的这个值累加起来以粗略估计服务器吞吐量。 
7.$http_referer :用来记录从那个页面链接访问过来的; 
8.$http_user_agent :记录客户端浏览器的相关信息;
9.$request : 请求内容
10.$status :请求状态吗
11.$http_user_agent: 客户端机型
12.$http_cookie客户端的cookie
13. $hostname 本主机服务器主机名
14.$upstream_addr 转发到哪里
15.$upstream_response_time : 转发响应时间
16.$request_time:整个请求的总时间。 
17.$server_name:虚拟主机名称
18.http_x_forwarded_for:客户端的真实ip,通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过$remote_add拿到的IP地址是反向代理服务器的iP地址。反向代理服务器在转发请求的http头信息中,可以增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址。
19. $ssl_cipher:交换数据中的算法,比如RC4-SHA


记录日志的access_log参数说明

access_log    off;  #关闭access_log,即不记录访问日志
    access_log path [format [buffer=size [flush=time]] [if=condition]];
    access_log path format gzip[=level] [buffer=size] [flush=time] [if=condition];
    access_log syslog:server=address[,parameter=value] [format [if=condition]];
    说明:
    buffer=size  #为存放访问日志的缓冲区大小
    flush=time  #为缓冲区的日志刷到磁盘的时间
    gzip[=level]  #表示压缩级别
    [if = condition]  #表示其他条件

主配置nginx.conf示例

image.png

虚拟机主机配置文件,www.conf示例

image.png


3.7 location

    location指令是根据用户请求的URI执行不同的应用,即根据用户请求的网站的地址URL进行匹配,匹配成功即进行相关操作

语法规则: location [=|~|~*|^~] /uri/ { … }

= 开头表示精确匹配

^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。

~ 开头表示区分大小写的正则匹配

~*  开头表示不区分大小写的正则匹配

!~和!~*分别为区分大小写不匹配及不区分大小写不匹配 的正则

/ 通用匹配,任何请求都会匹配到。


示例:

location = / {  
   #规则A  
}  
location = /login {  
   #规则B  
}  
location ^~ /static/ {  
   #规则C  
}  
location ~ \.(gif|jpg|png|js|css)$ {  
   #规则D  
}

    blog.conf配置如下

server {
        listen       82;            #监听端口
        server_name  blog.chucloud.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        location /documents/{
                return 403;
        }
        location ^~ /images/ {                #匹配任何以/images/开头查询并且停止搜索。任何正则表达式匹配将不会检查
                return 404;                   #^~作用是常规字符串匹配之后,不做正则表达式的检查,即如果最明确的那个字符串匹配location配置中有此前缀,那么不会做正则表达式的检查
        }
        location ~* \.(gif|jpg|jpeg)$ {        #匹配任何gif、jpg或者jpeg结尾的请求
                return 500;
        }
        access_log logs/access_www.log main gzip buffer=32k flush=5s;
}

image.png



在nginx的location和配置中location的顺序没有太大关系。正location表达式的类型有关。相同类型的表达式,字符串长的会优先匹配。

以下是按优先级排列说明:

  1. 等号类型(=)的优先级最高。一旦匹配成功,则不再查找其他匹配项。

  2. ^~类型表达式。一旦匹配成功,则不再查找其他匹配项。

  3. 正则表达式类型(~ ~*)的优先级次之。如果有多个location的正则能匹配的话,则使用正则表达式最长的那个。

  4. 常规字符串匹配类型。按前缀匹配。


3.8nginx rewrite

该功能主要是实现url地址重写。

指令语法:

rewrite regex replacement [falg];

默认值:none

应用值:server,location,if

根据regex部分内容,重定向到replacement部分,结尾是flag标记,简单例子如下

rewrite ^/(.*) /$1 permanent;

^/(.*) 正则表达式,表示匹配素有,匹配成功后跳转到http://bbs.chulcoud.com/$1 ,$1参数代表括号中部分  结尾permanent是永久301重定向


正则表达式

字符

描述

\

将后面接着的字符标记为一个特殊字符或一个原义字符或一个向后引用。如“\n”匹配一个换行符,而“\$”则匹配“$

^

匹配输入字符串的起始位置

$

匹配输入字符串的结束位置

*

匹配前面的字符零次或多次。如“ol*”能匹配“o”及“ol”、“oll

+

匹配前面的字符一次或多次。如“ol+”能匹配“ol”及“oll”、“oll”,但不能匹配“o

?

匹配前面的字符零次或一次,例如“do(es)?”能匹配“do”或者“does”,"?"等效于"{0,1}"

.

匹配除“\n”之外的任何单个字符,若要匹配包括“\n”在内的任意字符,请使用诸如“[.\n]”之类的模式。

(pattern)

匹配括号内pattern并可以在后面获取对应的匹配,常用$0...$9属性获取小括号中的匹配内容,要匹配圆括号字符需要\(Content\)


参数flag标记说明:

last  #本条规则匹配完成后,继续向下匹配新的location URI规则

break  #本条规则匹配完成即终止,不再匹配后面的任何规则

redirect  #返回302临时重定向,浏览器地址会显示跳转后的URL地址

permanent  #返回301永久重定向,浏览器地址栏会显示跳转后的URL地址


nginx rewrite 301跳转

实现www.chucloud.com和chucloud.com访问同一个地址

www.conf配置如下

server {
        listen       80;
        server_name  chucloud.com;
        rewite ^/(.*) http://www.chucloud.com/$1 permanent;    #当用户访问chucloud.com及下面任意内容的时候,都会通过这条rewrite跳转到www.chulcoud.com对应的地址
        location / {
            root   html/www;
            index  index.html index.htm;
        }
        access_log logs/access_www.log main gzip buffer=32k flush=5s;
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }


实现不同域名的url跳转

 实现http://blog.chucloud.com 跳转到http://www.chucloud.com/blog/blog.html

blog.conf 配置文件如下

server {
        listen       80;
        server_name  blog.chucloud.com;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
        if ($http_host ~* "^(.*)\.chucloud\.com$") {
           set $domain $1;
           rewrite ^(.*) http://www.chucloud.com/$domain/blog.html break;
           }

在/html/blog/下创建blog.html

cat >blog.html<<EOF
www.chucloud.com/blog/blog.html
well done
EOF

检查nginx语法重启

image.png

可以看到重定向生效,但是浏览器阻止了


3.9 nginx访问认证

 网站后台和一些关键网页需要设置网页认证,只有拥有账号的用户才能访问网站内容。

配置示例

location / {
    auth_basic            "clsed site"
    auth_basic_user_file conf/htpasswd;
    }

参数说明:

auth_basic

语法:auth_basic string | off;

默认值:auth_basic off;

使用位置:http、server、location 、limit_except

auth_basic_user_file

默认值:————

使用位置:http,server,location,limit_except

auth_basic_user_file 参数接认证密码文件,file 内容如下

#comment
name1:password1
name2:password2
name3:password3

bbs,conf 配置文件如下

server {
        listen       80;
        server_name  bbs.chucloud.com;
        location / {
            root   html/bbs;
            index  index.html index.htm;
            auth_basic                  "====>chucloud<====";
            auth_basic_user_file      /application/nginx/conf/htpasswd;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

生成账号密码步骤如下

yum install httpd-tools     #安装htppasswd

创建账号密码

[root@nginx1 extra]# htpasswd -bc /application/nginx/conf/htpasswd yangchao 123456
Adding password for user yangchao
[root@nginx1 extra]# chomd 400 /application/nginx/conf/htpasswd 
[root@nginx1 extra]# chmod 400 /application/nginx/conf/htpasswd 
[root@nginx1 extra]# chown nginx /application/nginx/conf/htpasswd

查看密码文件,发现是加密过了的

image.png

重启nginx生效

image.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章