LNMP系统——nginx

目录

一、安装

1、首先是依赖库的安装

2、命令获取安装包,需联网

3、编译安装前的准备

4、启动和查看运行情况

5、简单测试,先编辑主配置文件/application/nginx/conf/nginx.conf 

二、虚拟主机配置

1、基于域名的虚拟主机

2、基于IP的虚拟主机

3、基于端口的虚拟主机

三、nginx状态信息(nginx status)

四、nginx错误日志和访问日志

1、错误日志:

2、访问日志

日志格式定义(log_format)

日志记录定义(access_log)

3、日志测试

五、location

六、rewrite

七、nginx访问认证


 

本篇介绍nginx的搭建和关于web容器相关用法

为简化安装步骤,是在关闭iptables和selinux情况下进行

关闭selinux命令

sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config 

setenforce 0 

关闭iptables命令

/etc/init.d/iptables stop  

chkconfig iptables off 

一、安装

1、首先是依赖库的安装

[root@web01 ~]# yum install pcre pcre-devel openssl openssl-devel -y
[root@web01 ~]# rpm -qa pcre pcre-devel           
pcre-7.8-7.el6.x86_64
pcre-devel-7.8-7.el6.x86_64      
openssl-1.0.1e-57.el6.x86_64
openssl-devel-1.0.1e-57.el6.x86_64

 

2、命令获取安装包,需联网

这里使用的版本是nginx-1.6.3

包获取命令:wget -q http://nginx.org/download/nginx-1.6.3.tar.gz

也可将下载好的包直接拷贝或者上传到linux系统

 

[root@web01 tools]# wget -q http://nginx.org/download/nginx-1.6.3.tar.gz
[root@web01 tools]# ls -lh
总用量 788K
-rw-r--r-- 1 root root 787K 4月   8 2015 nginx-1.6.3.tar.gz
[root@web01 tools]# tar -zxvf nginx-1.6.3.tar.gz
[root@web01 tools]# ls
nginx-1.6.3  nginx-1.6.3.tar.gz

3、编译安装前的准备

解压tar包,和创建www用户

解压tar包
root@web01 tools]# tar -zxvf nginx-1.6.3.tar.gz
[root@web01 tools]# ls
nginx-1.6.3  nginx-1.6.3.tar.gz
[root@web01 tools]# cd nginx-1.6.3
创建用户www
[root@web01 nginx-1.6.3]# useradd www -s /sbin/nologin -M
[root@web01 nginx-1.6.3]# tail -n 1 /etc/passwd          
www:x:507:507::/home/www:/sbin/nologin

编译安装,这里简单介绍一下用到的编译参数,关于参数的更多更详细的介绍,可以使用 ./configure --help查看

--user=www         指定进程的用户

--group=www       指定进程的用户组

--with-http_ssl_module       激活ssl功能

--with-http_stub_status_module    激活状态信息(后文会详细介绍)

--prefix=/application/nginx-1.6.3/         指定安装路径

[root@web01 nginx-1.6.3]# ./configure --user=www --group=www   --with-http_ssl_module   --with-http_stub_status_module --prefix=/application/nginx-1.6.3/

[root@web01 nginx-1.6.3]# make
[root@web01 nginx-1.6.3]# make install

这里建立软连接是为了方便nginx版本升级,在其他应用中就不用做修改,重新做软连接即可
[root@web01 nginx-1.6.3]# ln -s /application/nginx-1.6.3/ /application/nginx

4、启动和查看运行情况

启动前先用 -t 参数检查语法(养成习惯),得到nginx.conf test is successful提示后在启动。

[root@web01 nginx-1.6.3]# /application/nginx/sbin/nginx -t
nginx: the configuration file /application/nginx-1.6.3//conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.6.3//conf/nginx.conf test is successful
[root@web01 nginx-1.6.3]# /application/nginx/sbin/nginx

检查是否启动
[root@web01 nginx-1.6.3]# netstat -lntup|grep nginx
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      8073/nginx 

检查端口         
[root@web01 nginx-1.6.3]# lsof -i :80 
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx   8073 root    6u  IPv4  17965      0t0  TCP *:http (LISTEN)
nginx   8074  www    6u  IPv4  17965      0t0  TCP *:http (LISTEN)

测试访问 200 ok 为正常应答 (这里关于HTTP协议,以后会专门拿一篇博客介绍)
[root@web01 nginx-1.6.3]# wget 127.0.0.1
--2019-04-22 00:56:56--  http://127.0.0.1/
正在连接 127.0.0.1:80... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:612 [text/html]
正在保存至: “index.html”

100%[=============================================================>] 612         --.-K/s   in 0s      

2019-04-22 00:56:56 (106 MB/s) - 已保存 “index.html” [612/612])

检查版本信息
[root@web01 nginx-1.6.3]# /application/nginx/sbin/nginx -V
nginx version: nginx/1.6.3
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC) 
TLS SNI support enabled
configure arguments: --user=www --group=www --with-http_ssl_module --with-http_stub_status_module --prefix=/application/nginx-1.6.3/

5、简单测试,先编辑主配置文件/application/nginx/conf/nginx.conf 

(每次修改过配置文件 ,需要重启nginx,或者reload)

[root@web01 conf]# cd /application/nginx/conf/
[root@web01 conf]# cat nginx.conf 
worker_processes  1;       #worker进程数
events {                  #事件区
    worker_connections  1024;     #每个worker进程支持的最大连接数
}
http {                          #http区块
    include       mime.types;   #nginx支持的媒体类型库文件
    default_type  application/octet-stream;  #默认的媒体类型
    sendfile        on;           #开启高效传输模式
    keepalive_timeout  65;        #连接超时
    server {                      #第一个server区块,表示一个独立站点,如笔者的www.ysm.org
        listen       80;          #提供服务的端口,默认80端口
        server_name www.ysm.org;  #站点的名字,域名
        location / {              #第一个location区(后文会介绍)
            root   html/www;     #默认首页文件目录,这里实际目录/application/nginx/html/www       
            index  index.html index.htm; #默认首页文件,多个用,分开。这些文件存放于html/www目录中
        }
    }
}

下面是笔者的index.html内容(第一次编写index.html,承让了QQ)ysm01.jpg 中是一个jpg图片,这里和index.html放在同一个目录

<html>
<head>
<title>天才的站点</title>
</head>
<body>
微笑
<table border=1>
<tr>
<td>ID</td>
<td>昵称</td>
</tr>
<tr>
<td>01</td>
<td>鲤鱼</td>
</tr>
<tr>
<td>02</td>
<td>无牙仔</td>
</tr>
</table>
<a href="http://www.ysm.org" target=_blank><img src="ysm01.jpg">ysm</a>
</body>
</html>

浏览器访问www.ysm.org效果。访问前,需要先在C:\Windows\System32\drivers\etc\hosts文件中添加域名解析,格式:IP  域名

如 172.16.1.08   www.ysm.org

二、虚拟主机配置

常见的三种主机类型:基于域名的虚拟主机、基于ip的虚拟主机、基于端口的虚拟主机

1、基于域名的虚拟主机

顾名思义,以不同的域名来区分不同的虚拟主机

配置案例,这里有3个server区块,分别代表域名为www.ysm.org、bbs.ysm.org、blog.ysm.org三个虚拟主机,通过不同的域名就可以分别访问者三个站点

[root@web01 conf]# cat nginx.conf.basename 
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name www.ysm.org;
        location / { 
            root   html/www;
            index  index.html index.htm;
        }
    }
    server {
          listen       80;
          server_name bbs.ysm.org;
          location / {
              root   html/bbs;
              index  index.html index.htm;
        }
    }
    server {
          listen       80;
          server_name blog.ysm.org;
          autoindex on;    #这个参数打开,表示没有找到index文件,则显示其(html/blog)目录结构
          location / {
              root   html/blog;
              index   ndex.html index.htm;
        }
    }
}

2、基于IP的虚拟主机

同基于域名的虚拟主机类似,但这里是通过不同的IP来区分虚拟主机

若网卡不够,则需要添加辅助IP,命令如下
[root@web01 conf]# ifconfig eth0:0 10.0.0.101/24 up
[root@web01 conf]# ip addr add 10.0.0.102/24 dev eth0 label eth0:1

若采基于ip的虚拟主机配置,同时有基于域名的配置,如下
访问bbs.ysm.org 将访问域名解析的ip地址虚拟主机

#这里只给出server区块,其他无变化
    server {
          listen      10.0.0.101:80;
          server_name bbs.ysm.org;
          location / {
              root   html/bbs;
              index  index.html index.htm;
        }
}

3、基于端口的虚拟主机

基于端口的虚拟主机则是通过不同的端口来区分不同的主机

通过IP访问必须加端口号,如10.0.0.101:81。如果不加端口号访问,则访问的是该配置文件中相同IP的第一个虚拟主机

#这里只给出server区块,其他无变化
    server {
          listen      10.0.0.101:81;
          server_name bbs.ysm.org;
          location / {
              root   html/bbs;
              index  index.html index.htm;
        }

三种虚拟主机可搭配使用,但是最常见的,还是基于域名和基于IP的

 

三、nginx状态信息(nginx status)

nginx状态信息属于 ngx_http_stub_status_module,在编译NGINX时必须增加http_stub_status_module模块

配置状态信息很简单,只需要新增一个server区块,把stub_status 打开即可,区块配置如下

#这里只给出server区块,其他的不变
##status
server{
  listen 80;
  server_name status.ysm.org; 
  location / {
    stub_status on;      
    access_log  off;  #关闭日志
  }
}

查看nginx状态信息图,

相关参数解释

Active connections: 4  :表示NGINX正在处理的活动连接数有4个

server    59           :表示NGINX启动到现在共处理了59个连接

accepts   59           :表示NGINX启动到现在共成功创建了59次握手

请求丢失数 = 握手数 – 连接数

handled requests 119   :表示共处理了119次请求

Reading 表示读取到客户端header信息数

Writing 表示返回给客户端的header信息数

Waiting 表示伊宁处理完正在等候下次请求指令的主流连接。在开启keep-alive的情况下,waiting = active - (reading + writing)

四、nginx错误日志和访问日志

 

1、错误日志:

属于核心功能模块ngx_http_core_module

语法:关键字(不可改变)    日志文件   错误日志级别       

error_log              file        level;

错误级别:[debug|info|notice|warn|error|crit|alert|emerg]由排列低到高,级别越高,记录的错误信息越少,一般使用warn|error|crit三个其中之一,如果配置低级别,会带来巨大的磁盘I/O消耗

error_log的默认值为:error_log  logs/error.log  error;

可以放在配置文件的main标签段,如后文示例

也可以放在http、server、location这些标签段

[root@web01 scripts]# cat /application/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}

error_log  logs/error.log  error;         #错误日志

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    
    server {
          listen      10.0.0.101:81;
          server_name bbs.ysm.org;
          location / {
              root   html/bbs;
              index  index.html index.htm;
        }
    }
}

2、访问日志

功能模块:ngx_http_log_module

日志格式定义(log_format)

语法:关键字(不可改变) 标签   日志信息变量(可记录多个)

         log_format      main   '$remote_addr - $remote_user [$time_local] "$request" ';

nginx日志参数表

$remote_addr

客户端的ip地址(代理服务器,显示代理服务ip)

$remote_user

用于记录远程客户端的用户名称(一般为“-”)

$time_local

用于记录访问时间和时区

$request

用于记录请求的url以及请求方法

$status

响应状态码,例如:200成功、404页面找不到等。

$body_bytes_sent

给客户端发送的文件主体内容字节数

$http_user_agent

用户所使用的代理(一般为浏览器)

$http_x_forwarded_for

可以记录客户端IP,通过代理服务器来记录客户端的ip地址

$http_referer

可以记录用户是从哪个链接访问过来的

配置位置在http标签内,如下

[root@web01 scripts]# cat /application/nginx/conf/nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}

error_log  logs/error.log  error;

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                   '$status $body_bytes_sent "$http_referer" '
                   '"$http_user_agent" "$http_x_forwarded_for"';  #访问日志格式定义

        server {
          listen      10.0.0.101:81;
          server_name bbs.ysm.org;
          location / {
              root   html/bbs;
              index  index.html index.htm;
          } 
           access_log logs/access_www.log main;  #指定以main格式开启访问日志
       }
}

日志记录定义(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]] ;

access_log off;

默认值: access_log logs/access.log combined;

配置段: http, server, location, if in location, limit_except

gzip[=level]压缩等级。

buffer=size设置内存缓存区大小。

flush=time保存在缓存区中的最长时间。

if=condition其他条件

一般场景这些参数都无需配置,极端优化才可能考虑这些参数

不记录日志:access_log off;

使用默认combined格式记录日志:access_log logs/access.log 或 access_log logs/access.log combined;

#这里只给出server区块,其他无变化
server {
        listen       80;
        server_name www.ysm.org ysm.org;
        location / {
            root   html/www;
            index  index.html index.htm;
        }
        access_log logs/access_www.log main;   #指定以main格式开启访问日志
}

3、日志测试

[root@web01 scripts]# /application/nginx/sbin/nginx -t

nginx: the configuration file /application/nginx-1.6.3//conf/nginx.conf syntax is ok

nginx: configuration file /application/nginx-1.6.3//conf/nginx.conf test is successful

[root@web01 extra]# /application/nginx/sbin/nginx -s reload

访问前,在hosts文件做本地的域名解析

windows:C:\Windows\System32\drivers\etc\hosts

linux:   /etc/hosts

hosts文件末尾添加解析记录,

格式:IP        域名

例如:10.0.0.8   www.ysm.org   

下图是windows浏览器访问结果

查看访问日志

[root@web01 html]# tail -n 5 /application/nginx/logs/access_www.log 
10.0.0.1 - - [23/Apr/2019:13:05:35 +0800] "GET /ysm01.jpg HTTP/1.1" 200 48239 "http://www.ysm.org/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36" "-"
10.0.0.1 - - [23/Apr/2019:13:06:52 +0800] "GET / HTTP/1.1" 200 318 "http://mmm.tiancai.org/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36" "-"
10.0.0.1 - - [23/Apr/2019:13:06:52 +0800] "GET /songlei.jpg HTTP/1.1" 404 570 "http://www.ysm.org/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36" "-"
10.0.0.1 - - [23/Apr/2019:13:07:18 +0800] "GET / HTTP/1.1" 200 316 "http://mmm.tiancai.org/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36" "-"
10.0.0.1 - - [23/Apr/2019:13:07:19 +0800] "GET /ysm01.jpg HTTP/1.1" 200 48239 "http://www.ysm.org/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36" "-"

这里再提供一个日志轮询的简单脚本

[root@web01 scripts]# vim cut_nginx_log.sh 
#!/bin/sh
Date=`date +%F -d '-1day'`
cd /application/nginx/logs &&\
/bin/mv access_www.log access_www_${Date}.log
/application/nginx/sbin/nginx -s reload
## rsync .....to backup server
## del date before 7 day
## find

加入定时任务,每天凌晨0点0分进行切割

[root@web01 scripts]# crontab -e        末尾添加如下内容

#####web cut nginx access_www.log####

0 0 * * * /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1

五、location

         location指令的作用,是根据用户请求的URI来执行不同的应用。也就是更具用户请求的网站地址URL进行匹配,成功匹配就进行相对应的操作

 

语法:location [ = | ~ | ~* | ^~ ] uri {

                   ………..

}

= 开头表示精确匹配

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

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

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

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

@ 内部调用

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

多个location配置的情况下匹配顺序为(参考资料而来,后面是实际验证,试试就知道,不必拘泥,仅供参考):

首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求。

#这里只给出修改的server区块
server {
        listen       80;
        server_name www.ysm.org ysm.org;    #添加了站点别名ysm.org,访问他和访问www.ysm.org是同一个网站
        root  html/www;

        location / {
            return 401;
        }
        location = / {
            return 402;
        }
        location /doucuments/ {
            return 403;
        }
        location ^~ /images/ {
            return 404;
        }
        location ~* \.(gif|jpg|jpeg)$ {
        return 500;
        }
        access_log logs/access_www.log main gzip buffer=32k flush=5s;
    }

笔者做的测试,用于对比匹配优先级

[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org
402
[root@web01 www]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/retregre
401
[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/index.html
401
[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/documents/ 
403
 [root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/documents/dafda
403
[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" 
http://www.ysm.org/images/q.gif
404
[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/documents/images/
403
[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/images/documents/
404
[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/documents/q.jpg
500
[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/ssss/q.jpg 
500
[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/images/documents/a.jpg
404
[root@web01 extra]# curl -s -o /dev/null -I -w "%{http_code}\n" http://www.ysm.org/documents/images/a.jpg
500

六、rewrite

rewrite比较复杂,这里只作一个permanent的URL跳转测试,具体rewrite的内容介绍将在下一片篇博文进行

文章地址:https://blog.csdn.net/qq_39014511/article/details/90287677

这里新增了一个server区块,站点域名是mmm.tiancai.org,当用户访问这个网址时,会通过rewrite重新定向到www.ysm.org这个网站
 

#这里只给出添加的server区块
server {

      listen       80;

      server_name mmm.tiancai.org;

      location / {

           rewrite ^/(.*) http://www.ysm.org/$1 permanent;

    }

}       

测试:

访问mmm.tiancai.org,会跳转到www.tiancai.org

访问mmm.tiancai.org/documents,会跳转到www.tiancai.org/documents

七、nginx访问认证

在实际工作中,有些网站只允许内部人员访问,这时候就需要为网站设置访问账号和密码,这样就只有拥有账号和

密码的用户才能访问。比如我们先前的nginx状态信息的网页,就可以设置账号密码,以防止外部人员获取我们的网站状态信息

这里用到两个参数

1、认证字符串提示:auth_basic

语法:  auth_basic   string | off;

默认值:auth_basic    off;

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

2、认证密码路径:auth_basic_user_file

语法: auth_basic_user_file      file;

默认值:—————

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

实例:

#这里只修改server区块    
server {
        listen       80;
        server_name www.ysm.org ysm.org;

        location / {
                auth_basic           "ysm password";   #认证字符串提示
                auth_basic_user_file /application/nginx/conf/htpasswd;   #认证密码路径
                root   html/www;
                index  index.html index.htm;
        }
        access_log logs/access_www.log main gzip buffer=32k flush=5s;

    }

在配置好主配置文件nginx.conf 之后,还需要添加账号和密码

通过htpasswd命令设置账号密码,认证密码路径/application/nginx/conf/htpasswd, 账号:ysm ,密码:123456

若没有htpasswd命令,执行yum install -y httpd

#安装和查看httpd
[root@web01 extra]# yum install httpd -y
[root@web01 extra]# rpm -qa httpd
httpd-2.2.15-69.el6.centos.x86_64
[root@web01 extra]# rpm -qf /usr/bin/htpasswd
httpd-tools-2.2.15-69.el6.centos.x86_64

#生成账号密码
[root@web01 extra]# htpasswd -cb /application/nginx/conf/htpasswd ysm 123456
#查看生成的密码文件,可以看到密码是加密的
[root@web01 extra]# cat /application/nginx/conf/htpasswd
ysm:3SP.ChgM4S7SU

把密码文件改为只读,然后重启nginx
[root@web01 extra]# chmod 400 /application/nginx/conf/htpasswd
[root@web01 extra]# /application/nginx/sbin/nginx -t
[root@web01 extra]# /application/nginx/sbin/nginx -s reload

浏览器访问站点(www.ysm.org)效果,不同的浏览器提示可能会有区别。

直接关掉这个窗口,将返回401错误

输入正确账号和密码,即可访问网站

在配置过程中,最容易碰到403问题,下面是可能导致403的原因

1 没有首页文件

2 没有读首页文件的权限

3 没有首页配置

4 设置访问认证,密码文件错误

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值