Nginx(一)初步认识及配置

Nginx的初步认识及配置

什么是Nginx?

  是一个高性能的反向代理服务器。(正向代理代理的是客户端,反向代理代理的是服务器)

与apache,tomcat区别

  nginx与apache是静态web服务器,本身只能解析静态资源(html,jpg),想解析动态资源需要依赖第三方模块;tomcat是动态服务器,可以解析(jsp,servlet)。
  apache资历老,但nginx支持高并发能力更强。

安装Nginx

  1. 下载tar包
  2. tar -zxvf nginx.tar.gz
  3. ./configure --prefix = (nginx安装路径)
  4. make && make install

启动和停止

./sbin目录下

  1. sbin/nginx
  2. ./nginx -s stop
  3. ./nginx -s reload

Nginx相关配置项解析

文件名:nginx.conf
路径:./conf/nginx.conf
配置项:

Main

event

http——虚拟主机配置

1. 基于ip的虚拟主机

不演示

2. 基于端口号的虚拟主机
server {
	listen 8080;
	server_name localhost;
	location / {
		root html;
		index index.html;
	}
}
3. 基于域名的虚拟主机
server{
	listen 80;
	server_name www.jeremy.com;
	location / {
		root html;
		index index.html;
	}
} 

因为没有注册域名,所以测试时还需要修改本机hosts文件虚拟域名访问效果。

location——访问路径

配置规则

location = /uri 精准匹配
location ^~ /uri 前缀匹配
location ~ /uri
location / 通用匹配

规则的优先级
  1. 精准匹配是优先级最高
  2. 普通匹配(最长的匹配优先)
  3. 正则匹配
实际使用建议
//精准匹配
location =/ {
	
}
//通用匹配
location / {
	
} 
//正则匹配——动静分离
location ~* \.(gif|....)${
	
}

Nginx模块

Nginx模块包括反向代理、email、nginx core。。。

模块分类

  1. 核心模块 ngx_http_core_module
  2. 标准模块 http模块
  3. 第三方模块

ngx_http_core_module

  1. location 实现uri到文件系统路径的映射
   server{
	    listen port
	    server_name
	    location{
	    }
    }
  1. error_page 状态码及对应路径
 error_page   500 502 503 504  /50x.html;
 location = /50x.html {
    root   html;
 }

ngx_http_access_module

实现基于ip的访问控制功能

  1. allow address | CIDR | unix: | all;
  2. deny address | CIDR | unix: | all;
    location / { deny alll; } //禁止所有路径访问

如何添加第三方模块

  1. 原来所安装的配置,需在重新安装新模块的时候,加上
  2. 不能直接make install

安装方法

  1. ./configure --prefix=/安装目录 --with - /第三方模块的目录
    ./configure --prefix=/data/program/nginx --with-http_stub_status_module --with-http_random_index_module
    
  2. make
  3. 将原有nginx配置拷贝到当前nginx目录下
    cp objs/nginx $nginx_home/sbin/nginx
    
  4. make install

接下来,介绍两个第三方nginx模块:

http_stub_status_module

location /status {
	stub_status;
}

访问结果:
在这里插入图片描述
Active connections:当前状态,活动状态的连接数
accepts:统计总值,已经接受的客户端请求的总数
handled:统计总值,已经处理完成的客户端请求的总数
requests:统计总值,客户端发来的总的请求数
Reading:当前状态,正在读取客户端请求报文首部的连接的连接数
Writing:当前状态,正在向客户端发送响应报文过程中的连接数
Waiting:当前状态,正在等待客户端发出请求的空闲连接数

http_random_index_module

  随机显示主页
  一般情况下,一个站点默认首页都是定义好的index.html、index.shtml等等,如果想站点下有很多页面想随机展示给用户浏览,那得程序上实现,很麻烦,使用nginx的random index即可简单实现这个功能,凡是以’ / '结尾的请求,都会随机展示当前目录下的文件作为首页。

  1. 添加random_index on 配置,默认是关闭的
location / {
	root html;
	random_index on;
	index index.html index.htm;
}
  1. 在html目录下创建多个html页面

猜你喜欢

转载自blog.csdn.net/JeremyJiaming/article/details/88111017