nginx(web)应用实践

简介:

nginx的配置:
    nginx的主要目录介绍:
        conf (这要配置文件)
        sbin(命令)
        logs(日志文件)
        html网站的主要目录的存放位置(一般安装后查找nginx下面的 HTML目录)该目录默认放置网站的代码。)
    Nginx的主配置文件nginx.conf 整个文件是以块状的形式组织的。
        我们过滤掉#和空格来看下主配置文件内容
        # grep -Ev "#|^$" nginx.conf | cat -n
             1  worker_processes  1;    #worker进程的数量
             2  events {
             3      worker_connections  1024;  #每个worker进程支持的最大连接数
             4  }
             5  http {
             6      include       mime.types;  #nginx支持的媒体类型库文件
             7      default_type  application/octet-stream;
             8      sendfile        on;         #开启高速传输模式
             9      keepalive_timeout  65;      #连接超时
            10      server {                    #表示一个独立虚拟主机站点。如果配置多个需要操作配置server
            11          listen       80;        #提供服务的端口
            12          server_name  localhost; #提供服务的主机域名
            13          location / {            
            14              root   html;        #虚拟主机的根目录。nginx安装目录下的html目录
            15              index  index.html index.htm;   #默认的首页文件。多个用空格隔开
            16          }
            17          error_page   500 502 503 504  /50x.html;
                                                #出现对应的http状态码时,使用50x.html回应客户。
            18          location = /50x.html {
            19              root   html;
            20          }
            21      }
            22  }
        第1行为:main 区域  第2-4行是events区域。这2个区域是nginx的核心
        5-22为nginx http的核心区域 其中包括10-21是server区域(而 13-16和18-20这2个location被server包含)
        每个区域块以{大括号 开始  以 } 大括号结束。
    nginx虚拟主机配置:
        所谓虚拟主机,在web服务器里就是一个独立的网站站点。这个站点对应独立的域名(或者端口也或者ip和端口),
        具有独立的程序和目录,可以独立地对外提供服务供用户访问。
        apache下每个虚拟主机由<VirtualHost></VirtualHost>包含,而Nginx软件由server{}来标记。
        虚拟主机的类型包含三类:
        1.基于域名的虚拟主机 2.基于端口的虚拟主机 3.基于ip的虚拟主机
    1.配置基于域名的虚拟主机实验:
        #    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;
        #        }   
        #    }   
            server {

                listen       80; 
                server_name  www.swallow.com;  #修改域名
                location / { 
                    root   html/www;       #修改虚拟主机的根目录
                    index  index.html index.htm;
                }   
                error_page   500 502 503 504  /50x.html;
                location = /50x.html {
                    root   html/www;        #修改虚拟主机的根目录
                }   
            }   
    配置基于 www.swallow.com 的虚拟主机目录:
        # tree /application/nginx/html/
            /application/nginx/html/
            ├── 50x.html
            ├── index.html
            └── www
                ├── 50x.html
                └── index.html
    # mkdir  -p   ../html/wwww
    # cp ./html/*.html ./html/www  (根据配置文件创建目录和文件)
    # echo "this is swallow" >./html/www/index.html
    检测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@swallow nginx]# ./sbin/nginx -s reload
    构建本地hosts
    # echo "192.168.1.120 www.swallow.com">> /etc/hosts
    # curl www.swallow.com
    this is swallow
    配置多个基于域名的虚拟主机:
        只需要修改server{}里面的 servername      root 
        创建 新增域名对应的站点目录及文件。# vim ./conf/nginx.conf
        server {
        listen       80; 
        server_name  blog.swallow.blog;
        location / { 
            root   html/blog;
            index  index.html index.htm;
        }   
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html/blog;
        }   
        }   
        server {
            listen       80  
            server_name  bbs.swallow.com;
            location / { 
                root   html/bbs;
                index  index.html index.htm;
            }   
            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                root   html/bbs;
            }   
        }   
    # for n in blog bbs; do mkdir -p ./html/$n; echo "http://$n.swallow.com" > ./html/$n/index.html; cp ./html/50x.html ./html/$n/; done
    将新域名加入/etc/hosts 解析
    检查配置文件重新平滑启动nginx
    测试结果:
    # curl www.swallow.com blog.swallow.com bbs.swallow.com
    http:www.swallow.com
    http:blog.swallow.com    
    http:bbs.swallow.com  
    curl的扩展:(-I 是提取返回状态的头部信息。利用这个头部信息的检测可以知道nginx是否成功开启)
    # curl -I -s --connect-timeout 2 www.swallow.com |head -1
    HTTP/1.1 200 OK   
    2.配置基于端口的虚拟主机:
    修改nginx.conf 配置文件里面的server{}下的 listen 改成 任意数值(不可与应用的端口冲突。)
    检测nginx配置文件,平滑重启:测试的时候需要 域名:端口 或者 ip:端口
    3.配置基于ip的的虚拟主机;
    修改nginx.conf 配置文件在多域名的基础上修改server{}的listen  改成ip:端口
    (因为每个虚拟主机在启动时,要占用一个端口。多个一起启动时,要开启多个端口。

优化多域名的虚拟主机配置:
        优点是:方便管理虚拟主机。减少配置文件之间的耦合性,避免因为一个虚拟主机的修改错误影响整个nginx服务。
        原理是:将写在一个配置文件的多个虚拟主机拆分成独立的配置文件。然后在住配置文件中进行引用(include)。
        # cd ./conf
        # mkdir extra
        # sed -n '22,33p' nginx.conf   (查看虚拟主机www的配置文件)
            server {
                listen       80;
                server_name  www.swallow.com;
                location / {
                    root   html/www;
                    index  index.html index.htm;
                }
                error_page   500 502 503 504  /50x.html;
                location = /50x.html {
                    root   html/www;
                }
            }
        # sed -n '22,33p' nginx.conf > ./extra/www.conf (生成新的配置文件)
        # sed -n '34,45p' nginx.conf>./extra/blog.conf   
        # sed -n '46,57p' nginx.conf>./extra/bbs.conf
        最后在源文件中删除 这些配置文件模块,并且使用include 将他们引用进去。
        # sed -i '22,57d' nginx.conf
        # sed -i ' 22 i include extra/www.conf;\ninclude extra/bbs.conf;\ninclude extra/blog.conf;' nginx.conf
        查看新的配置文件:(注释部分是模版。新的虚拟主机就是在这个基础上改成的)
            # cat nginx.conf -n
             1  worker_processes  1;
             2  events {
             3      worker_connections  1024;
             4  }
             5  http {
             6      include       mime.types;
             7      default_type  application/octet-stream;
             8      sendfile        on;
             9      keepalive_timeout  65;
            10  #    server {
            11  #        listen       80;
            12  #        server_name  localhost;
            13  #        location / {
            14  #            root   html;
            15  #            index  index.html index.htm;
            16  #        }
            17  #        error_page   500 502 503 504  /50x.html;
            18  #        location = /50x.html {
            19  #            root   html;
            20  #        }
            21  #    }
            22  include extra/www.conf;
            23  include extra/bbs.conf;
            24  include extra/blog.conf;
            25  }

        # ../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
        # ../sbin/nginx -s reload
        # curl www.swallow.com bbs.swallow.com blog.swallow.com
        http:www.swallow.com
        http:bbs.swallow.com
        http:blog.swallow.com
    优化成功。这个可以避免频繁修改主配置文件的繁琐。如果那个虚拟主机需要更改配置。可以简单的修改单个文件,
        然后include 进入住文件。在多个虚拟主机时。方便管理。

错误日志功能:nginx错误日志一般分为 debug |info|notice |warn |error|crit|alert|emerg 这几个级别。
        一般 运行 warn |error|crit 这2个级别。默认开启 crit 级别。建议开启error。
        这里不要把级别调的太低。会产生大量的日志。消耗磁盘I/O。更多的查看访问日志。
        可以配置在 main  ,http , server , location 这几个区域快中。
        在主配置文件的main区域 添加一行  error_log logs/error.log error;

访问日志功能;
        # sed -n '21,23 s/#//gp' nginx.conf.default 
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
        将这段格式信息加载到http模块中
        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_user_agent" "$http_x_forwarded_for"';
            sendfile        on;
            keepalive_timeout  65;
        #    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;
        #        }
        #    }
        include extra/www.conf; 
        include extra/bbs.conf;
        include extra/blog.conf;
        }   
    简要解析访问日志格式参数:
        $remote_addr 记录访问网站的客户端地址
        $remote_user 远程客户端名称
        $time_Local 记录访问时间和时区
        $request 用户http请求起始行信息
        $status http 请求返回状态码
        $body_bytes_sents 服务器发送给客户端的响应body字节数
        $http_referer 记录此次请求是从哪个链接访问过来的。根据 referer防盗链
        $http_user_agent 记录客户端访问信息
    然后在 虚拟主机中开启访问日志:(在单个的虚拟机配置:在server的最后面添加
                                    access_log logs/access_$name.log main;

        # vim extra/www.conf 
            server {
                listen       80;
                server_name  www.swallow.com;
                location / {
                    root   html/www;
                    index  index.html index.htm;
                }
                error_page   500 502 503 504  /50x.html;
                location = /50x.html {
                    root   html/www;
                }
                access_log logs/access_www.log main;
            }
    在开启访问日志后,日志文件的体积会越来越大。不便于对日志分析和处理。需要轮询切割日志。
        思路是:把每日的文件以日期重命名。写入crond 。按时执行。
        # vim cut_nginx_bbs.sh
        #!/bin/bash
        Dateformat=`date +%Y%m%d`
        Basedir="/application/nginx"
        Lognginxdir="$Basedir/logs"
        Logname="access_bbs"
        [ -d ${Lognginxdir} ] && cd ${Lognginxdir} || exit 1
        [ -f ${Logname}.log ] || exit 2
        /bin/mv ${Logname}.log ${Dateformat}_${Logname}.log
        $Basedir/sbin/nginx -s reload

location作用:根据用户请求的URL来执行不同的应用。根据用户请求网址的URL进行匹配。匹配成功,进程相应的操作
      匹配的两种特殊字符"~"或"~*" "~"区分大小写 "~*" 不区分大小写."!"表示取反
      "^~"作用:在进行常规匹配后不做正则表达式的检查。

用户请求的URL说明及顺序

用户请求的URL

设置的状态码

说明

这里省略所有的前缀:http://www.swallow.com

当为空或/时

Location = / {

 }

=精确匹配,优先级最高

/images/1.gif

Location ^~ /images/ {

}

匹配常规字符,不做正则匹配^~作用:优先匹配路径,而不会匹配1.gif

/docment/1.jpg

Location ~* \.(gif|jpg|jpeg)$ {

}

这里是正则匹配。匹配了

1.jpg

/document/document.html

Location /document/ {

}

常规匹配,如果有正则则优先匹配正则。匹配了/document

/index.html或是任何不匹配location模块的字符串

Location / {

}

/默认匹配,所有location都匹配不上后的,默认匹配

Nginx rewrite
        主要功能实现URL地址重写。(需要pcre支持)
        语法指令:   rewrite regex  replacement [flag];
        应用位置: server  location  if
        rewrite 是实现URL重写的关键指令,根据regex(正则表达式)的部分的内容,重定向到replacement部分,结尾是flag标记。

Regex常用正则表达式

字符

描述

\

将后面接着的字符标记为一个特殊字符或一个原以字符或一个向后引用  。例如”\n”匹配一个换行符

^

匹配输入字符的起始位置

$

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

*

匹配0个或多个字符。等价于 {0,}(贪婪模式)

+

匹配1个或多个字符。等价于{1,}(贪婪模式)

?

匹配0个或1个,如果根贪婪模式一起,会限制贪婪模式。

例如“0000”,“0+?”则匹配“0”。而“0+”则匹配“0000”

.

匹配除”\n”外的任意单个字符,如果要匹配”\n”要使用[.\n]

(pattern)

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

Rewrite最后一项参数flag标记的说明

Flag标记符号

说明

Last

浏览器地址栏不变,服务器的路径改变

本条规则匹配完成后,向下匹配新的location URL规则

Break

本条规则匹配完成后,不再匹配后面的任何规则

Redirect

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

Permanent

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

案例实现301跳转
        server {
        listen 80;
        server_name swa.com;
        rewrite ^/(.*) http://www.swa.com/$1 permanent;
        }
     server {
        listen 80;
        server_name www.swa.com;
        location /{
                root html;
                index index.html index.htm;
        }
        }
    测试结果:
    # curl -I swa.com
    HTTP/1.1 301 Moved Permanently
    Server: nginx/1.6.3
    Date: Tue, 31 Jan 2017 23:47:26 GMT
    Content-Type: text/html
    Content-Length: 184
    Connection: keep-alive
    Location: http://www.swa.com/
实现不同域名的URL跳转:
    要求网站访问http://blog.swallow.com 时,跳转至http://www.swallow.com/blog/blog.com
    在 conf/extra/blog.conf 添加:
     12    if ( $http_host ~* "^(.*)\.swallow\.com$"){
     13         set $domain $1;
     14         rewrite ^(.*) http://www.swallow.com/$domain/blog.html break;
     15       }
    测试结果:
    # curl -I blog.swallow.com
    HTTP/1.1 302 Moved Temporarily
    Server: nginx/1.6.3
    Date: Wed, 01 Feb 2017 00:14:18 GMT
    Content-Type: text/html
    Content-Length: 160
    Connection: keep-alive
    Location: http://www.swallow.com/blog/blog.html
    要求网站访问:访问http://www.swallow.com/blog时,跳转至http://blog.swallow.com
    在 conf/extra/www.conf 添加
    rewrite ^(.*)/blog http://blog.swallow.com break;
    测试结果:
    # curl -I www.swallow.com/blog
    HTTP/1.1 302 Moved Temporarily
    Server: nginx/1.6.3
    Date: Wed, 01 Feb 2017 00:37:37 GMT
    Content-Type: text/html
    Content-Length: 160
    Connection: keep-alive
    Location: http://blog.swallow.com

nginx 访问认证:
    在主配置文件 中加入
    auth_basic "swallow training" ;#提示信息,说明网站需要访问认证
    auth_basic_user_file /application/nginx/conf/htpasswd;  #存放用户名和密码的地方
    生成认证帐号和生成密码
    htpasswd (如果没有可以  # yum install httpd -y  是apache服务带来的命令)
    # htpasswd -bc /application/nginx/conf/htpasswd swa 555555
    # chmod 400 /application/nginx/conf/htpasswd 
    # chown nginx /application/nginx/conf/htpasswd










本文转自 swallow_zys  51CTO博客,原文链接:http://blog.51cto.com/12042068/1894511,如需转载请自行联系原作者
相关实践学习
基于函数计算快速搭建Hexo博客系统
本场景介绍如何使用阿里云函数计算服务命令行工具快速搭建一个Hexo博客。
目录
相关文章
|
14天前
|
前端开发 JavaScript 关系型数据库
从前端到后端:构建现代化Web应用的技术探索
在当今互联网时代,Web应用的开发已成为了各行各业不可或缺的一部分。从前端到后端,这篇文章将带你深入探索如何构建现代化的Web应用。我们将介绍多种技术,包括前端开发、后端开发以及各种编程语言(如Java、Python、C、PHP、Go)和数据库,帮助你了解如何利用这些技术构建出高效、安全和可扩展的Web应用。
|
29天前
|
监控 Serverless 测试技术
Serverless 应用引擎常见问题之做的web服务计费如何解决
Serverless 应用引擎(Serverless Application Engine, SAE)是一种完全托管的应用平台,它允许开发者无需管理服务器即可构建和部署应用。以下是Serverless 应用引擎使用过程中的一些常见问题及其答案的汇总:
401 3
|
1月前
|
前端开发 数据库 UED
构建高性能Web应用的关键技术
本文将介绍构建高性能Web应用的关键技术,包括前端优化、后端优化、数据库优化等方面。通过深入讨论各项技术的原理和实践方法,帮助开发者们提升Web应用的响应速度和用户体验。
|
28天前
|
前端开发 应用服务中间件 nginx
使用Docker快速搭建Web服务器Nginx
本文指导如何使用Docker快速搭建Nginx服务器。首先,通过`docker pull`命令获取Nginx镜像,然后以容器形式运行Nginx并映射端口。通过挂载目录实现本地文件与容器共享,便于自定义网页。使用`docker ps`检查运行状态,访问IP:8088确认部署成功。最后,介绍了停止、删除Nginx容器的命令,强调Docker简化了服务器部署和管理。
42 0
|
7天前
|
缓存 负载均衡 数据库
优化后端性能:提升Web应用响应速度的关键策略
在当今数字化时代,Web应用的性能对于用户体验至关重要。本文探讨了如何通过优化后端架构和技术手段,提升Web应用的响应速度。从数据库优化、缓存机制到异步处理等多个方面进行了深入分析,并提出了一系列实用的优化策略,以帮助开发者更好地应对日益增长的用户访问量和复杂的业务需求。
9 1
|
7天前
|
缓存 监控 数据库
Flask性能优化:打造高性能Web应用
【4月更文挑战第16天】本文介绍了提升Flask应用性能的七大策略:优化代码逻辑,减少数据库查询,使用WSGI服务器(如Gunicorn、uWSGI),启用缓存(如Flask-Caching),优化数据库操作,采用异步处理与并发(如Celery、Sanic),以及持续监控与调优。通过这些手段,开发者能有效优化Flask应用,适应大型或高并发场景,打造高性能的Web服务。
|
8天前
|
数据库 开发者 Python
Python中使用Flask构建简单Web应用的例子
【4月更文挑战第15天】Flask是一个轻量级的Python Web框架,它允许开发者快速搭建Web应用,同时保持代码的简洁和清晰。下面,我们将通过一个简单的例子来展示如何在Python中使用Flask创建一个基本的Web应用。
|
12天前
|
JavaScript 前端开发 API
Vue.js:构建高效且灵活的Web应用的利器
Vue.js:构建高效且灵活的Web应用的利器
|
20天前
|
XML JSON JavaScript
使用JSON和XML:数据交换格式在Java Web开发中的应用
【4月更文挑战第3天】本文比较了JSON和XML在Java Web开发中的应用。JSON是一种轻量级、易读的数据交换格式,适合快速解析和节省空间,常用于API和Web服务。XML则提供更强的灵活性和数据描述能力,适合复杂数据结构。Java有Jackson和Gson等库处理JSON,JAXB和DOM/SAX处理XML。选择格式需根据应用场景和需求。
|
30天前
|
机器学习/深度学习 前端开发 算法
利用机器学习优化Web前端性能的探索与实践
本文将介绍如何利用机器学习技术来优化Web前端性能,探讨机器学习在前端开发中的应用,以及通过实际案例展示机器学习算法对前端性能优化的效果。通过结合前端技术和机器学习,提升Web应用的用户体验和性能表现。