马哥教育网络20期—nginx

Nginx

一. Nginx 特性
二. Nginx 基本架构
三. Nginx 基本功能
四. Nginx 安装
五. Nginx 配置文件
六. Nginx http服务功能测试
七. Nginx LNMP

一. Nginx 特性

  • 模块化,目前只能将模块编译进Nginx,暂时不支持动态装卸载模块.(httpd优势)

  • 可靠性,一个主进程(master)控制多个工作进程(worker),工作进程响应用户多个请求(httpd劣势)

  • 低内存消耗,(httpd劣势)

  • 支持热部署,(httpd一样)

  • 支持事件驱动I/O,AI/O,支持mmap(httpd2.4才算支持event,劣势)

二. Nginx 基本架构

Nginx由一个master进程生成多个worker进程,每个worker进程接收用户请求,支持sendfile,AIO,mmap,

43.png

三. Nginx 基本功能

  • 静态资源WEB服务器,能缓存打开的文件描述符

  • http,反向代理服务器,缓存服务器,负载均衡服务器

  • 支持fastcgi(php),uwsgi(python)与动态程序结合

  • 支持ssl传输

  • 支持虚拟主机

  • 支持keepalive

  • 支持平滑升级

  • 支持定制日志,日志缓存

  • 支持url重写

  • 支持路径别名

  • 支持限速,并发控制

  • look look www.nginx.org

四. Nginx 安装

~]# yum install pcre-devel openssl-devel -y
~]# groupadd -r nginx
~]# useradd -r -g nginx -s /sbin/nologin -M nginx
~]# cd /usr/src/
src]# tar xf nginx-1.8.1.tar.gz
src]# cd nginx-1.8.1
nginx-1.8.1]# ./configure --prefix=/usr/local/nginx \
--conf-path=/etc/nginx/nginx.conf \
--user=nginx --group=nginx \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/var/run/nginx/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-http_flv_module \
--with-http_mp4_module \
--http-client-body-temp-path=/var/tmp/nginx/client \
--http-proxy-temp-path=/var/tmp/nginx/proxy \
--http-fastcgi-temp-path=/var/tmp/nginx/fastcgi
nginx-1.8.1]# make && make install
nginx-1.8.1]# mkdir -pv /var/tmp/nginx/{client,proxy,fastcgi}
nginx-1.8.1]# cd /usr/local/nginx
nginx]# ll  #才两个目录,当然,我们的配置文件和log文件存放在其他目录,可见nginx多轻量级
total 8
drwxr-xr-x 2 root root 4096 Jun 24 23:34 html
drwxr-xr-x 2 root root 4096 Jun 24 23:34 sbin
nginx]# cd ~
~]# echo "export PATH=/usr/local/nginx/sbin:$PATH" > /etc/profile.d/nginx.sh    #准备nginx程序执行是的环境变量
~]# mkdir .vim
~]# cp -ra /usr/src/nginx-1.8.1/contrib/vim/* .vim/     #设置nginx配置文件的语法着色,
~]# . /etc/profile.d/nginx.sh
~]# nginx   #启动nginx

五. nginx配置文件

~]# cd /etc/nginx/
[root@node2 nginx]# ll
total 60
-rw-r--r-- 1 root root 1034 Jun 24 07:21 fastcgi.conf           #FPM配置文件段
-rw-r--r-- 1 root root 1034 Jun 24 07:21 fastcgi.conf.default
-rw-r--r-- 1 root root  964 Jun 24 07:21 fastcgi_params
-rw-r--r-- 1 root root  964 Jun 24 07:21 fastcgi_params.default
-rw-r--r-- 1 root root 2837 Jun 24 07:21 koi-utf
-rw-r--r-- 1 root root 2223 Jun 24 07:21 koi-win
-rw-r--r-- 1 root root 3957 Jun 24 07:21 mime.types             #mime类型配置文件
-rw-r--r-- 1 root root 3957 Jun 24 07:21 mime.types.default
-rw-r--r-- 1 root root 2656 Jun 24 07:21 nginx.conf             #nginx主配置文件
-rw-r--r-- 1 root root 2656 Jun 24 07:21 nginx.conf.default
-rw-r--r-- 1 root root  596 Jun 24 07:21 scgi_params
-rw-r--r-- 1 root root  596 Jun 24 07:21 scgi_params.default
-rw-r--r-- 1 root root  623 Jun 24 07:21 uwsgi_params           #uwsgi配置文件段
-rw-r--r-- 1 root root  623 Jun 24 07:21 uwsgi_params.default
-rw-r--r-- 1 root root 3610 Jun 24 07:21 win-utf
nginx的配置文件主要分为两段:main http
main主要是控制nginx程序的运行
http主要是操作web服务器,且http配置段下还可以继续分为server段(虚拟主机)
配置文件分段即可把分段的配置文件从主文件剥离出来,形成单独的配置文件,并且只要在主配置文件中include此配置文件即可,比如说server虚拟主机配置文件段
================================
主配置段:
user  nginx nginx;      #worker进程运行的属主与属组
worker_processes  3;    #worker进程数,建议与CPU核心数少1
pid        /var/run/nginx/nginx.pid;    #指定pid文件位置
worker_rlimit_nofile 50000;             #显示所有worker进程所能打开的文件数目
worker_cpu_affinity 0001 0010 0100;     #绑定CPU,八核cpu就8个0,
events {
    worker_connections  10240;          #每个worker进程所能并发处理的连接数
}

http配置段:
include       mime.types;       #包含mime配置文件所有配置内容
sendfile        on;             #开启sendfile功能
keepalive_timeout  65;          #开启长连接

server配置段:
listen       80;                #监听端口
server_name  localhost;         #服务器名字
location{}                      #针对匹配到不同的url可以下发不同的配置段
gzip  on;                       #开启gzip压缩

六. Nginx http服务功能测试

  1. root path

  2. location [ = | ~ | ~* | ^~ ] uri { … }

  3. alias path

  4. error_page

  5. ssl

  6. stu_status内置状态页面

  7. url重写

  8. if语法

  9. 定制日志

root path
root是指定网页文件存放的路径,可以在server配置段,也可以在location配置段,
存在location配置段时:
    绝对路径:优先级最高  
    root /vhosts/web/;
    location / {
        root   /vhosts/web1;            #访问的是/vhosts/web1/index.html
        index  index.html index.htm;
    }
    相对路径:是相对于nginx安装路径目录下html
    root /vhosts/web/;
    location / {
        root   html;                    #相对路径,访问的是/usr/local/nginx/html/index.html,
        index  index.html index.htm;
    }
存在server配置段时:location建议不要配置.
    root /vhosts/web/;                  #此时才是访问/vhosts/web/index.html
    location / {
        index  index.html index.htm;    
    }
location [ = | ~ | ~* | ^~ ] uri { … }
符号表示匹配后面uri的优先级,[=] > [^~] > [~|~*] >不带任何修饰符,其中[~]表示区分大小写,[~*]表示不区分大小写
测试图片,图片本身就标注了存放位置:

46.png

测试目录:
[root@node2 vhosts]# tree
.
├── a.png
├── web1
│   ├── documents
│   │   └── a.png
│   └── images
│       └── a.png
├── web2
│   ├── documents
│   │   └── a.png
│   └── images
│       └── a.png
└── web3
    ├── documents
    │   └── a.png
    └── images
        └── a.png
测试配置:
location /documents/ {
    root /vhosts/web1;
    index  index.html index.htm;
}
location ^~ /images/ {
    root /vhosts/web2;
    index  index.html index.htm;
}
location ~* \.(png|jpg|jpeg)$ {
    root /vhosts/web3;
    index  index.html index.htm;
}
location = /a.png {
    root /vhosts;
    index  index.html index.htm;
}
测试结果:
当我们访问:192.168.3.20/images/a.png
说明:根据我们的URL[/images/a.png],服务器匹配location事先定义好的url,可以匹配到第二个与第三个location,因为[^~] > [~*],所在才有看到的是/vhosts/web2/images/a.png

44.png

当我们访问:192.168.3.20/documents/a.png
说明:根据我们的URL[/documents/a.png],服务器匹配location事先定义好的url,可以匹配到第一个与第三个location,因为[~|~*] >不带任何修饰符,所以才看到的是/vhosts/web3/documents/a.png

45.png

[=]的匹配也可以参考如上说明,
结论:匹配方式是根据用户输入的URL部分去匹配我们定义的location,当URL可以匹配到多个location的时候,就有了优先级的定义,

优先级:[=] > [^~] > [~|~] >不带任何修饰符*

alias path
访问资源是的URL与实际资源存储位置不一样,就需要别名定义实际存储位置,
location /documents/ {
    alias /vhosts/web1/;
    index  index.html index.htm;
}
当我们访问192.168.3.20/documents/时,显示的却是:

47.png

error_page
根据http响应状态码来指明特定的错误页面
location / {
    root /vhosts/web1/;
    index  index.html index.htm;
}
error_page  404     /404.html;      #当访问不存在的资源时,就会回应404错误代码,根据404错误代码会显示特定的404.html,这个页面是存在与/vhosts/web1/目录下

48.png

ssl
编译时需要选择此模块 --with-http_ssl_module(httpd程序是需要安装mod_ssl模块,并且配置是在ssl配置文件中配置)
CA服务器生成私钥,自己对自己签名
CA]# touch index.txt
CA]# echo 01 > serial
CA]# (umask 077; openssl genrsa -out private/cakey.pem 2048;)
CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 3560   
客户端服务器生成私钥,并且生成证书申请请求
~]# mkdir /usr/local/nginx/ssl
~]# cd /usr/local/nginx/ssl
ssl]# openssl genrsa -out node2.key 1024
ssl]# openssl req -new -key node2.key -out node2.csr -days 365
ssl]# scp node2.csr root@ns1:/tmp/node2.csr
CA服务器对客户端传送过来的证书请求签发
CA]# openssl ca -in /tmp/node2.csr -out ./certs/node2.stu.com.crt -days 365
CA]# scp certs/node2.stu.com.crt root@node2:/usr/local/nginx/ssl/
Nginx服务器配置支持ssl,我们在编译此nginx服务器时就包括了
server {
    listen       443 ssl;
    server_name  localhost;
    ssl_certificate      /usr/local/nginx/ssl/node2.stu.com.crt;    #从CA申请过来的证书
    ssl_certificate_key  /usr/local/nginx/ssl/node2.key;            #私钥
    ssl_session_cache    shared:SSL:1m;                             #ssl会话共享缓存,1分钟时间
    ssl_session_timeout  5m;                                        #ssl会话超时时间5分钟
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;
    location / {
        root /vhosts/web1;
        index index.html index.htm;
    }
}

49.png

50.png

stu_status内置状态页面
在location中定义:
location /nginx-status {
    allow 192.168.3.0/24;       #基于IP地址访问控制
    deny all;
    stub_status on;             #开启状态页面
    access_log off;             #关闭状态页面的访问日志
}
测试访问:
[root@node3 nginx]# curl http://node2.stu.com/nginx-status
Active connections: 2 
server accepts handled requests
 235 235 1239 
Reading: 0 Writing: 1 Waiting: 1
=====解释如下=====
Active connections:当前所有处于打开状态的连接数
accepts:已经接收进来的连接
handled:已经处理过的连接
requests:已经处理过的请求数
Reading:正处于接收请求状态的连接数
Writing:请求已经接收完成,正处于处理请求或发送响应过程的连接数
Waiting:保持连接且处理于活动状态的连接数
url重写
将用户请求特定资源的URL路径修改重定向到其他路径,(break,last,redirect,permanent是可选参数)
location / {
    root /vhosts/web2;
    rewrite /documents/(.*\.png)$ /images/$1 break;     #将访问/vhosts/web2/documents/路径下以.png结尾的资源,全部重定向到/vhosts/web2/images/
    index  index.html index.htm;
}

51.png

break:一旦对此rewrute规则重写后,由user agent对新的url重新发起新的请求,且不会在被location内的rewrite规则检查,
last:一旦对此rewrute规则重写后,由user agent对新的url重新发起新的请求,如果还有被location内的rewrite匹配中那么就继续重写URL,这是多么痛的领悟,
location / {
    root /vhosts/web2;
    rewrite /documents/(.*\.png)$ /images/$1 last;      #采用last,重写后的URL会匹配到下面一条location规则,并且还会被在重写,
    index  index.html index.htm;
}
location ^~ /images/ {                                  #利用^~强行将URL的images抓到此location下进行URL重写
    root /vhosts/web1/;
    rewrite /images/(.*\.png)$ /documents/$1 break;     #用户输入node2.stu.com/documents/a.png最后其实访问的是/vhosts/web1/documents/a.png
    index  index.html index.htm;
}

52.png

redirect:以302状态响应码(临时重定向),返回新的URL,
location / {
    root /vhosts/web2;
    rewrite /documents/(.*\.png)$ /images/$1 redirect;
    index  index.html index.htm;
}

53.png

permanent:以301 #状态响应码(永久重定向),返回新的URL,
location / {
    root /vhosts/web2;
    rewrite /documents/(.*\.png)$ /images/$1 permanent;
    index  index.html index.htm;
}

54.png

if语法
if语句的语法:if(condition) {},应用位置:server,location配置段
condition:
1. 变量赋值:禁止变量赋值为空或者以"0"开头,其他都OK
2. 以变量为操作数构成的比较表达式,可使用=,!=类似操作符比较
3. 正则表达式的模式匹配操作
    ~:区分大小写
    ~*:不区分大小写
    !~和!~*对上面两种测试取反
4. 测试路径为文件的可能性:-f | !-f
5. 测试指定路径为目录的可能性:-d | !-d
6. 测试文件存在性:-e | !-e
7. 检查文件是否有执行权限:-x | !-x
location / {
    root /vhosts/web2;
    if ($http_user_agent ~* Chrome) {       #如果是谷歌浏览器就把URL重写到/vhosts/web2/images/index.html
        rewrite ^(.*)$ /images/$1 break;
    }
    index  index.html index.htm;
}

55.png

Embedded Variables
$http_user_agent
$http_cookie
$connection             #connection serial number (1.3.8, 1.2.5)
$connection_requests    #current number of requests made through a connection (1.3.8, 1.2.5) 
$content_length         #“Content-Length” request header field
$content_type           #“Content-Type” request header field 
$cookie_name            #the name cookie
$host                   #in this order of precedence: host name from the request line, or host name from the “Host” request header field, or the server name matching a request 
$hostname               #host name 
$nginx_version          #nginx version 
$pid                    #PID of the worker process 
$remote_addr            #client address 
$remote_port            #client port 
$remote_user            #user name supplied with the Basic authentication 
$time_local             #local time in the Common Log Format (1.3.12, 1.2.7) 
$server_name            #name of the server which accepted a request 
$server_port            #port of the server which accepted a request 
$server_protocol        #request protocol, usually “HTTP/1.0”, “HTTP/1.1”, or “HTTP/2.0” 
look look www.nginx.org  http://nginx.org/en/docs/http/ngx_http_core_module.html
======防盗链=====
valid_referers none blocked server_names
           *.example.com example.* www.example.org/galleries/
           ~\.google\.;
    if ($invalid_referer) {     #invalid_referer表示该用户是从哪个位置链接过来本网站的
        return 403;
}
定制日志
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;    #上面定义的日志在此处调用,定义日志信息的变量都是内置变量

七.Nginx LNMP

PHP程序可以作为Apache的httpd模块运行,也可以通过FPM的方式与httpd联动.
而PHP程序与Nginx程序联动只能以FPM的方式.
准备Mariadb:
src]# tar xf mariadb-5.5.46-linux-x86_64.tar.gz
src]# ln -sv /usr/src/mariadb-5.5.46-linux-x86_64 /usr/local/mysql
src]# cd /usr/local/mysql
mysql]# groupadd -r mysql
mysql]# useradd -r -g mysql -s /sbin/nologin -M mysql
mysql]# chown -R mysql:mysql .
mysql]# mkdir -pv /mydata/data
mysql]# chown -R mysql:mysql /mydata/data
mysql]# scripts/mysql_install_db --user=mysql --datadir=/mydata/data
mysql]# chown -R root .
mysql]# cp support-files/mysql.server /etc/rc.d/init.d/mysqld
mysql]# chkconfig --add mysqld
mysql]# chkconfig mysqld on
mysql]# mkdir /etc/mysql
mysql]# cp support-files/my-large.cnf /etc/mysql/my.conf
mysql]# vi /etc/mysql/my.conf
    datadir=/mydata/data
mysql]# echo "export PATH=/usr/local/mysql/bin:$PATH" > /etc/profile.d/mysql.sh     #还有include文件,库文件,man文件没有做链接.
mysql]# . /etc/profile.d/mysql.sh
mysql]# service mysqld restart                                      #遇到一个错误,PID file not found ,重启之后就可以了,用ps -aux | grep mysqld 都看不到任何mysqld的进程
MySQL server PID file could not be found!                  [FAILED]
Starting MySQL..                                           [FAILED]
mysql]# service mysqld start
Starting MySQL..                                           [  OK  ]
=====安装php=====
php-5.4.26]# cd /usr/src/php-5.4.26
php-5.4.26]# yum install pcre-devel openssl-devel libxml2-devel php-gd freetype-devel libjpeg-devel libpng-devel bzip2-devel libmcrypt-devel -y
php-5.4.26]# ./configure --prefix=/usr/local/php --with-mysql=/usr/local/mysql --with-openssl --with-mysqli=/usr/local/mysql/bin/mysql_config --enable-mbstring --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml  --enable-sockets --enable-fpm --with-mcrypt  --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2
php-5.4.26]# make -j 4 && make install
php-5.4.26]# cp php.ini-production /etc/php.ini
php-5.4.26]# cp sapi/fpm/init.d.php-fpm /etc/rc.d/init.d/php-fpm
php-5.4.26]# chmod +x /etc/rc.d/init.d/php-fpm
php-5.4.26]# chkconfig --add php-fpm
php-5.4.26]# chkconfig php-fpm on
php-5.4.26]# cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf
php-5.4.26]# vi /usr/local/php/etc/php-fpm.conf
    pm.max_children = 50
    pm.start_servers = 5
    pm.min_spare_servers = 2                    #这个数值不能大于start_server,想想知道,不然php服务起不来
    pm.max_spare_servers = 8
    pid = /usr/local/php/var/run/php-fpm.pid 
php-5.4.26]# service php-fpm start
======配置nginx支持php=====
location ~ \.php$ {
    root           /vhosts/web4/;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /vhosts/web4$fastcgi_script_name;       #需要指定我们指定存放php程序网站的路径
    include        fastcgi_params;
}
上传phpmyadmin测试(怎么是这个鬼样子,原来是浏览器的缘故谷歌不会):

56.png

57.png

(虚拟主机部分实验忘记做了= =!)

OK,告一段落。

原创文章,作者:nice_neo_linux,如若转载,请注明出处:http://www.178linux.com/19901

(0)
上一篇 2016-06-26 22:42
下一篇 2016-06-26 22:43

相关推荐

  • LVS DR模式

    一、测试环境说明 操作系统:CentOS6.7-X64 IP_VS版本:1.2.26 DR:10.10.10.130 VIP:10.10.10.140 RS1:10.10.10.131 RS2:10.10.10.132 二、LVS-DR模式原理 a)客户端发送一个请求(源地址为CIP,目标地址为VIP,我们简称为CIP:VIP)到LVS的DR b)通过在调度…

    Linux干货 2016-09-19
  • nginx在linux系统应用详解之一基础介绍和全局配置

    一、nginx简介       1、特点:           (1)nginx服务器既可以作为HTTP服务器,也可以作为反向代理服务器,还可以作为邮件服务器;           (2)能够快速响应静态页面的请求;  …

    2017-06-19
  • CentOS6下的网络信息配置

    简介     我们都知道在我们互联网中,所有的通信都通过网络来完成的,有了网络当然也要有对应的地址,MAC地址是固定不变的,所以能变的只有IP的地址,那么今天来带给大家如何在CentOS6中如何配置网卡。当然一下的所有命令都是在CentOS6中进行的。 一、网卡的配置文件    1.操作网卡的命令 …

    Linux干货 2017-03-20
  • nfs服务部署wordpress

    NFS服务简介 NFS 是Network File System的缩写,即网络文件系统。一种使用于分散式文件系统的协定,由Sun公司开发,于1984年向外公布。功能是通过网络让不同的机器、不同的操作系统能够彼此分享个别的数据,让应用程序在客户端通过网络访问位于服务器磁盘中的数据,是在类Unix系统间实现磁盘文件共享的一种方法。 NFS 的基本原则是“容许不同…

    2017-04-28
  • N26-第三周博客

    1、列出当前系统上所有已经登录的用户的用户名,注意:同一个用户登录多次,则只 显示一次即可。 [yang@localhost /]$ who | cut -d" " -f 1 | sort -u 2、取出最后登录到当前系统的用户的相关信息。 [root@localhost tmp]# last | head -1 3、取出当前系…

    Linux干货 2017-02-08
  • DNS转发、ACL以及VIEW

    DNS全称是Domain Name System的简称,即域名系统。因特网上作为域名和IP地址相互映射的一个分布式数据库,能够使用户更方便的访问互联网,而不用去记住能够被机器直接读取的IP数串。通过主机名,最终得到该主机名对应的IP地址的过程叫做域名解析(或主机名解析)。DNS协议运行在UDP/TCP协议之上,使用端口号53。 DNS转发、ACL以及VIEW…

    Linux干货 2016-12-08