nginx的使用

nginx是什么?
nginx是一个开源的,支持高性能,高并发的www服务和代理服务软件。它是一个俄罗斯人lgor sysoev开发的,作者将源代码开源出来供全球使用。
nginx比它大哥apache性能改进许多,nginx占用的系统资源更少,支持更高的并发连接,有更高的访问效率。
nginx不但是一个优秀的web服务软件,还可以作为反向代理,负载均衡,以及缓存服务使用。
安装更为简单,方便,灵活。
nginx的优点:
支持高并发,能支持几万并发连接
资源消耗少,在3万并发连接下开启10个nginx线程消耗的内存不到200M
可以做http反向代理和负载均衡
支持异步网络i/o事件模型epoll

 

1.下载配置nginx软件

(1)解决nginx所需的依赖包(在opt目录下)
yum install gcc patch libffi-devel python-devel  zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel openssl openssl-devel -y
(2)下载源码包
wget -c https://nginx.org/download/nginx-1.12.0.tar.gz
(3)解压缩源码
tar -zxvf nginx-1.12.0.tar.gz
(4)配置,编译安装 ,开启nginx状态监测功能(先进入到nginx-1.12.0文件夹)
./configure --prefix=/opt/nginx1-12/ 
(5)make && make install 

查看nginx的工作目录

conf  nginx的配置文件目录
html  网页根目录
logs  日志
sbin  存放nginx可执行命令

2.快速复制出一个小的网页

进入nginx112目录下的html文件夹,在文件夹中找到index.html文件
找到像替换的网页的源代码,替换该文件

随意找的源代码

<style>
@import url('https://fonts.googleapis.com/css?family=Press+Start+2P');

body {
  margin: 0;
  font-family: 'Press Start 2P', cursive;
  font-size: 2em;
  color: white;
}
button {
  outline: none;
  cursor: pointer;
}
#counter {
  position: absolute;
  top: 20px;
  right: 20px;
}
#end {
  position: absolute;
  min- 100%;
  min-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  visibility: hidden;
}
#end button {
  background-color: red;
  padding: 20px 50px 20px 50px;
  font-family: inherit;
  font-size: inherit;
}
#controlls {
  position: absolute;
  min- 100%;
  min-height: 100%;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
#controlls div {
  margin-bottom: 20px;
  font-size: 0;
  max- 180px;
}
#controlls button {
   50px;
  font-family: inherit;
  font-size: 30px;
  border: 3px solid white;
  color: white;
  background-color: transparent;
  margin: 5px;
}
#controlls button:first-of-type {
   170px;
}
</style>


<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/99/three.min.js"></script>
<a style="color:red";href="https://www.cnblogs.com/pyyu/">博客园地址:https://www.cnblogs.com/pyyu/ 点我呀 老弟</a>
<div id="counter">0</div>
<div id="controlls">
  <div>
    <button id="forward" style="color:black">↑向前</button>
    <button id="left" style="color:black">←向左</button>
    <button id="backward" style="color:black">↓向下</button>
    <button id="right" style="color:black">→向右</button>
  </div>
</div>

<div id="end">
  <button id="retry">Retry</button>
</div>


<script>
const counterDOM = document.getElementById('counter');  
const endDOM = document.getElementById('end');  

const scene = new THREE.Scene();

const distance = 500;
const camera = new THREE.OrthographicCamera( window.innerWidth/-2, window.innerWidth/2, window.innerHeight / 2, window.innerHeight / -2, 0.1, 10000 );

camera.rotation.x = 50*Math.PI/180;
camera.rotation.y = 20*Math.PI/180;
camera.rotation.z = 10*Math.PI/180;

const initialCameraPositionY = -Math.tan(camera.rotation.x)*distance;
const initialCameraPositionX = Math.tan(camera.rotation.y)*Math.sqrt(distance**2 + initialCameraPositionY**2);
camera.position.y = initialCameraPositionY;
camera.position.x = initialCameraPositionX;
camera.position.z = distance;

const zoom = 2;

const chickenSize = 15;

const positionWidth = 42;
const columns = 17;
const boardWidth = positionWidth*columns;

const stepTime = 200; // Miliseconds it takes for the chicken to take a step forward, backward, left or right

let lanes;
let currentLane;
let currentColumn;

let previousTimestamp;
let startMoving;
let moves;
let stepStartTimestamp;

const carFrontTexture = new Texture(40,80,[{x: 0, y: 10, w: 30, h: 60 }]);
const carBackTexture = new Texture(40,80,[{x: 10, y: 10, w: 30, h: 60 }]);
const carRightSideTexture = new Texture(110,40,[{x: 10, y: 0, w: 50, h: 30 }, {x: 70, y: 0, w: 30, h: 30 }]);
const carLeftSideTexture = new Texture(110,40,[{x: 10, y: 10, w: 50, h: 30 }, {x: 70, y: 10, w: 30, h: 30 }]);

const truckFrontTexture = new Texture(30,30,[{x: 15, y: 0, w: 10, h: 30 }]);
const truckRightSideTexture = new Texture(25,30,[{x: 0, y: 15, w: 10, h: 10 }]);
const truckLeftSideTexture = new Texture(25,30,[{x: 0, y: 5, w: 10, h: 10 }]);

const generateLanes = () => [-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9].map((index) => {
    const lane = new Lane(index);
    lane.mesh.position.y = index*positionWidth*zoom;
    scene.add( lane.mesh );
    return lane;
}).filter((lane) => lane.index >= 0);

const addLane = () => {
    const index = lanes.length;
    const lane = new Lane(index);
    lane.mesh.position.y = index*positionWidth*zoom;
    scene.add(lane.mesh);
    lanes.push(lane);
}

const chicken = new Chicken();
scene.add( chicken );

const laneTypes = ['car', 'truck', 'forest'];
const laneSpeeds = [2, 2.5, 3];
const vechicleColors = [0xa52523, 0xbdb638, 0x78b14b];
const threeHeights = [20,45,60];

const initaliseValues = () => {
    lanes = generateLanes()

    currentLane = 0;
    currentColumn = Math.floor(columns/2);

    previousTimestamp = null;

    startMoving = false;
    moves = [];
    stepStartTimestamp;

    chicken.position.x = 0;
    chicken.position.y = 0;

    camera.position.y = initialCameraPositionY;
    camera.position.x = initialCameraPositionX;
}

initaliseValues();

const renderer = new THREE.WebGLRenderer({
  alpha: true,
  antialias: true
});
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
scene.add(hemiLight)

dirLight = new THREE.DirectionalLight(0xffffff, 0.6);
dirLight.position.set(-100, -100, 200);
dirLight.castShadow = true;
scene.add(dirLight);

dirLight.shadow.mapSize.width = 2048;
dirLight.shadow.mapSize.height = 2048;
var d = 500;
dirLight.shadow.camera.left = - d;
dirLight.shadow.camera.right = d;
dirLight.shadow.camera.top = d;
dirLight.shadow.camera.bottom = - d;

// var helper = new THREE.CameraHelper( dirLight.shadow.camera );
// var helper = new THREE.CameraHelper( camera );
// scene.add(helper)

backLight = new THREE.DirectionalLight(0x000000, .4);
backLight.position.set(200, 200, 50);
backLight.castShadow = true;
scene.add(backLight)

function Texture(width, height, rects) {
    const canvas = document.createElement( "canvas" );
    canvas.width = width;
    canvas.height = height;
    const context = canvas.getContext( "2d" );
    context.fillStyle = "#ffffff";
    context.fillRect( 0, 0, width, height );
    context.fillStyle = "rgba(0,0,0,0.6)";  
    rects.forEach(rect => {
      context.fillRect(rect.x, rect.y, rect.w, rect.h);
    });
    return new THREE.CanvasTexture(canvas);
}

function Wheel() {
    const wheel = new THREE.Mesh( 
      new THREE.BoxBufferGeometry( 12*zoom, 33*zoom, 12*zoom ), 
      new THREE.MeshLambertMaterial( { color: 0x333333, flatShading: true } ) 
    );
    wheel.position.z = 6*zoom;
    return wheel;
}

function Car() {
  const car = new THREE.Group();
  const color = vechicleColors[Math.floor(Math.random() * vechicleColors.length)];
  
  const main = new THREE.Mesh(
    new THREE.BoxBufferGeometry( 60*zoom, 30*zoom, 15*zoom ), 
    new THREE.MeshPhongMaterial( { color, flatShading: true } )
  );
  main.position.z = 12*zoom;
  main.castShadow = true;
  main.receiveShadow = true;
  car.add(main)
  
  const cabin = new THREE.Mesh(
    new THREE.BoxBufferGeometry( 33*zoom, 24*zoom, 12*zoom ), 
    [
      new THREE.MeshPhongMaterial( { color: 0xcccccc, flatShading: true, map: carBackTexture } ),
      new THREE.MeshPhongMaterial( { color: 0xcccccc, flatShading: true, map: carFrontTexture } ),
      new THREE.MeshPhongMaterial( { color: 0xcccccc, flatShading: true, map: carRightSideTexture } ),
      new THREE.MeshPhongMaterial( { color: 0xcccccc, flatShading: true, map: carLeftSideTexture } ),
      new THREE.MeshPhongMaterial( { color: 0xcccccc, flatShading: true } ), // top
      new THREE.MeshPhongMaterial( { color: 0xcccccc, flatShading: true } ) // bottom
    ]
  );
  cabin.position.x = 6*zoom;
  cabin.position.z = 25.5*zoom;
  cabin.castShadow = true;
  cabin.receiveShadow = true;
  car.add( cabin );
  
  const frontWheel = new Wheel();
  frontWheel.position.x = -18*zoom;
  car.add( frontWheel );

  const backWheel = new Wheel();
  backWheel.position.x = 18*zoom;
  car.add( backWheel );

  car.castShadow = true;
  car.receiveShadow = false;
  
  return car;  
}

function Truck() {
    const truck = new THREE.Group();
    const color = vechicleColors[Math.floor(Math.random() * vechicleColors.length)];
    

    const base = new THREE.Mesh(
        new THREE.BoxBufferGeometry( 100*zoom, 25*zoom, 5*zoom ), 
        new THREE.MeshLambertMaterial( { color: 0xb4c6fc, flatShading: true } )
    );
    base.position.z = 10*zoom;
    truck.add(base)

    const cargo = new THREE.Mesh(
      new THREE.BoxBufferGeometry( 75*zoom, 35*zoom, 40*zoom ), 
      new THREE.MeshPhongMaterial( { color: 0xb4c6fc, flatShading: true } )
    );
    cargo.position.x = 15*zoom;
    cargo.position.z = 30*zoom;
    cargo.castShadow = true;
    cargo.receiveShadow = true;
    truck.add(cargo)

    const cabin = new THREE.Mesh(
      new THREE.BoxBufferGeometry( 25*zoom, 30*zoom, 30*zoom ), 
      [
        new THREE.MeshPhongMaterial( { color, flatShading: true } ), // back
        new THREE.MeshPhongMaterial( { color, flatShading: true, map: truckFrontTexture } ),
        new THREE.MeshPhongMaterial( { color, flatShading: true, map: truckRightSideTexture } ),
        new THREE.MeshPhongMaterial( { color, flatShading: true, map: truckLeftSideTexture } ),
        new THREE.MeshPhongMaterial( { color, flatShading: true } ), // top
        new THREE.MeshPhongMaterial( { color, flatShading: true } ) // bottom
      ]
    );
    cabin.position.x = -40*zoom;
    cabin.position.z = 20*zoom;
    cabin.castShadow = true;
    cabin.receiveShadow = true;
    truck.add( cabin );
    
    const frontWheel = new Wheel();
    frontWheel.position.x = -38*zoom;
    truck.add( frontWheel );
  
    const middleWheel = new Wheel();
    middleWheel.position.x = -10*zoom;
    truck.add( middleWheel );

    const backWheel = new Wheel();
    backWheel.position.x = 30*zoom;
    truck.add( backWheel );
    
    return truck;  
  }

function Three() {
    const three = new THREE.Group();
    
    const trunk = new THREE.Mesh(
      new THREE.BoxBufferGeometry( 15*zoom, 15*zoom, 20*zoom ), 
      new THREE.MeshPhongMaterial( { color: 0x4d2926, flatShading: true } )
    );
    trunk.position.z = 10*zoom;
    trunk.castShadow = true;
    trunk.receiveShadow = true;
    three.add(trunk);

    height = threeHeights[Math.floor(Math.random()*threeHeights.length)];

    const crown = new THREE.Mesh(
        new THREE.BoxBufferGeometry( 30*zoom, 30*zoom, height*zoom ), 
        new THREE.MeshLambertMaterial( { color: 0x7aa21d, flatShading: true } )
    );
    crown.position.z = (height/2+20)*zoom;
    crown.castShadow = true;
    crown.receiveShadow = false;
    three.add(crown);
    
    return three;  
}

function Chicken() {
    const chicken = new THREE.Group();
    
    const body = new THREE.Mesh(
      new THREE.BoxBufferGeometry( chickenSize*zoom, chickenSize*zoom, 20*zoom ), 
      new THREE.MeshPhongMaterial( { color: 0xffffff, flatShading: true } )
    );
    body.position.z = 10*zoom;
    body.castShadow = true;
    body.receiveShadow = true;
    chicken.add(body);

    const rowel = new THREE.Mesh(
        new THREE.BoxBufferGeometry( 2*zoom, 4*zoom, 2*zoom ), 
        new THREE.MeshLambertMaterial( { color: 0xF0619A, flatShading: true } )
    );
    rowel.position.z = 21*zoom;
    rowel.castShadow = true;
    rowel.receiveShadow = false;
    chicken.add(rowel);
    
    return chicken;  
}

function Road() {
    const road = new THREE.Group();

    const createSection = color => new THREE.Mesh(
        new THREE.PlaneBufferGeometry( boardWidth*zoom, positionWidth*zoom ), 
        new THREE.MeshPhongMaterial( { color } )
    );

    const middle = createSection(0x454A59);
    middle.receiveShadow = true;
    road.add(middle);

    const left = createSection(0x393D49);
    left.position.x = - boardWidth*zoom;
    road.add(left);

    const right = createSection(0x393D49);
    right.position.x = boardWidth*zoom;
    road.add(right);
    
    return road;
}

function Grass() {
    const grass = new THREE.Group();

    const createSection = color => new THREE.Mesh(
        new THREE.BoxBufferGeometry( boardWidth*zoom, positionWidth*zoom, 3*zoom ), 
        new THREE.MeshPhongMaterial( { color } )
    );

    const middle = createSection(0xbaf455);
    middle.receiveShadow = true;
    grass.add(middle);

    const left = createSection(0x99C846);
    left.position.x = - boardWidth*zoom;
    grass.add(left);

    const right = createSection(0x99C846);
    right.position.x = boardWidth*zoom;
    grass.add(right);

    grass.position.z = 1.5*zoom;
    return grass;
}

function Lane(index) {
    this.index = index;
    this.type = index <= 0 ? 'field' : laneTypes[Math.floor(Math.random()*laneTypes.length)];

    switch(this.type) {
        case 'field': {
            this.type = 'field';
            this.mesh = new Grass();
            break;
        }
        case 'forest': {
            this.mesh = new Grass();
            
            this.occupiedPositions = new Set();
            this.threes = [1,2,3,4].map(() => {
                const three = new Three();
                let position;
                do {
                    position = Math.floor(Math.random()*columns);
                }while(this.occupiedPositions.has(position))
                this.occupiedPositions.add(position);
                three.position.x = (position*positionWidth+positionWidth/2)*zoom-boardWidth*zoom/2;
                this.mesh.add( three );
                return three;
            })
            break;
        }
        case 'car' : {
            this.mesh = new Road();
            this.direction = Math.random() >= 0.5;
            
            const occupiedPositions = new Set();
            this.vechicles = [1,2,3].map(() => {
                const vechicle = new Car();
                let position;
                do {
                    position = Math.floor(Math.random()*columns/2);
                }while(occupiedPositions.has(position))
                occupiedPositions.add(position);
                vechicle.position.x = (position*positionWidth*2+positionWidth/2)*zoom-boardWidth*zoom/2;
                if(!this.direction) vechicle.rotation.z = Math.PI;
                this.mesh.add( vechicle );
                return vechicle;
            })

            this.speed = laneSpeeds[Math.floor(Math.random()*laneSpeeds.length)];
            break;
        }
        case 'truck' : {
            this.mesh = new Road();
            this.direction = Math.random() >= 0.5;
            
            const occupiedPositions = new Set();
            this.vechicles = [1,2].map(() => {
                const vechicle = new Truck();
                let position;
                do {
                    position = Math.floor(Math.random()*columns/3);
                }while(occupiedPositions.has(position))
                occupiedPositions.add(position);
                vechicle.position.x = (position*positionWidth*3+positionWidth/2)*zoom-boardWidth*zoom/2;
                if(!this.direction) vechicle.rotation.z = Math.PI;
                this.mesh.add( vechicle );
                return vechicle;
            })

            this.speed = laneSpeeds[Math.floor(Math.random()*laneSpeeds.length)];
            break;
        }
    }
}

document.querySelector("#retry").addEventListener("click", () => {
    lanes.forEach(lane => scene.remove( lane.mesh ));
    initaliseValues();
    endDOM.style.visibility = 'hidden';
});

document.getElementById('forward').addEventListener("click", () => move('forward'));

document.getElementById('backward').addEventListener("click", () => move('backward'));

document.getElementById('left').addEventListener("click", () => move('left'));

document.getElementById('right').addEventListener("click", () => move('right'));

window.addEventListener("keydown", event => {
    if (event.keyCode == '38') {
        // up arrow
        move('forward');
    }
    else if (event.keyCode == '40') {
        // down arrow
        move('backward');
    }
    else if (event.keyCode == '37') {
       // left arrow
       move('left');
    }
    else if (event.keyCode == '39') {
       // right arrow
       move('right');
    }
});

function move(direction) {
    const finalPositions = moves.reduce((position,move) => {
        if(move === 'forward') return {lane: position.lane+1, column: position.column};
        if(move === 'backward') return {lane: position.lane-1, column: position.column};
        if(move === 'left') return {lane: position.lane, column: position.column-1};
        if(move === 'right') return {lane: position.lane, column: position.column+1};
    }, {lane: currentLane, column: currentColumn})

    if (direction === 'forward') {
        if(lanes[finalPositions.lane+1].type === 'forest' && lanes[finalPositions.lane+1].occupiedPositions.has(finalPositions.column)) return;
        if(!stepStartTimestamp) startMoving = true;
        addLane();
    }
    else if (direction === 'backward') {
        if(finalPositions.lane === 0) return;
        if(lanes[finalPositions.lane-1].type === 'forest' && lanes[finalPositions.lane-1].occupiedPositions.has(finalPositions.column)) return;
        if(!stepStartTimestamp) startMoving = true;
    }
    else if (direction === 'left') {
       if(finalPositions.column === 0) return;
       if(lanes[finalPositions.lane].type === 'forest' && lanes[finalPositions.lane].occupiedPositions.has(finalPositions.column-1)) return;
       if(!stepStartTimestamp) startMoving = true;
    }
    else if (direction === 'right') {
       if(finalPositions.column === columns - 1 ) return;
       if(lanes[finalPositions.lane].type === 'forest' && lanes[finalPositions.lane].occupiedPositions.has(finalPositions.column+1)) return;
       if(!stepStartTimestamp) startMoving = true;
    }
    moves.push(direction);
}

function animate(timestamp) {
    requestAnimationFrame( animate );
    
    if(!previousTimestamp) previousTimestamp = timestamp;
    const delta = timestamp - previousTimestamp;
    previousTimestamp = timestamp;
  
    // Animate cars and trucks moving on the lane
    lanes.forEach(lane => {
        if(lane.type === 'car' || lane.type === 'truck') {
            const aBitBeforeTheBeginingOfLane = -boardWidth*zoom/2 - positionWidth*2*zoom;
            const aBitAfterTheEndOFLane = boardWidth*zoom/2 + positionWidth*2*zoom;
            lane.vechicles.forEach(vechicle => {
                if(lane.direction) {
                    vechicle.position.x = vechicle.position.x < aBitBeforeTheBeginingOfLane ? aBitAfterTheEndOFLane : vechicle.position.x -= lane.speed/16*delta;
                }else{
                    vechicle.position.x = vechicle.position.x > aBitAfterTheEndOFLane ? aBitBeforeTheBeginingOfLane : vechicle.position.x += lane.speed/16*delta;
                }
            });
        }
    });

    if(startMoving) {
        stepStartTimestamp = timestamp;
        startMoving = false;
    }

    if(stepStartTimestamp) {
        const moveDeltaTime = timestamp - stepStartTimestamp;
        const moveDeltaDistance = Math.min(moveDeltaTime/stepTime,1)*positionWidth*zoom;
        const jumpDeltaDistance = Math.sin(Math.min(moveDeltaTime/stepTime,1)*Math.PI)*8*zoom;
        switch(moves[0]) {
            case 'forward': {
                camera.position.y = initialCameraPositionY + currentLane*positionWidth*zoom + moveDeltaDistance;        
                chicken.position.y = currentLane*positionWidth*zoom + moveDeltaDistance; // initial chicken position is 0
                chicken.position.z = jumpDeltaDistance;
                break;
            }
            case 'backward': {
                camera.position.y = initialCameraPositionY + currentLane*positionWidth*zoom - moveDeltaDistance;
                chicken.position.y = currentLane*positionWidth*zoom - moveDeltaDistance;
                chicken.position.z = jumpDeltaDistance;
                break;
            }
            case 'left': {
                camera.position.x = initialCameraPositionX + (currentColumn*positionWidth+positionWidth/2)*zoom -boardWidth*zoom/2 - moveDeltaDistance;        
                chicken.position.x = (currentColumn*positionWidth+positionWidth/2)*zoom -boardWidth*zoom/2 - moveDeltaDistance; // initial chicken position is 0
                chicken.position.z = jumpDeltaDistance;
                break;
            }
            case 'right': {
                camera.position.x = initialCameraPositionX + (currentColumn*positionWidth+positionWidth/2)*zoom -boardWidth*zoom/2 + moveDeltaDistance;        
                chicken.position.x = (currentColumn*positionWidth+positionWidth/2)*zoom -boardWidth*zoom/2 + moveDeltaDistance; 
                chicken.position.z = jumpDeltaDistance;
                break;
            }
        }
        // Once a step has ended
        if(moveDeltaTime > stepTime) {
            switch(moves[0]) {
                case 'forward': {
                    currentLane++;
                    counterDOM.innerHTML = currentLane;    
                    break;
                }
                case 'backward': {
                    currentLane--;
                    counterDOM.innerHTML = currentLane;    
                    break;
                }
                case 'left': {
                    currentColumn--;
                    break;
                }
                case 'right': {
                    currentColumn++;
                    break;
                }
            }
            moves.shift();
            // If more steps are to be taken then restart counter otherwise stop stepping
            stepStartTimestamp = moves.length === 0 ? null : timestamp;
        }
    }

    // Hit test
    if(lanes[currentLane].type === 'car' || lanes[currentLane].type === 'truck') {
        const chickenMinX = chicken.position.x - chickenSize*zoom/2;
        const chickenMaxX = chicken.position.x + chickenSize*zoom/2;
        const vechicleLength = { car: 60, truck: 105}[lanes[currentLane].type]; 
        lanes[currentLane].vechicles.forEach(vechicle => {
            const carMinX = vechicle.position.x - vechicleLength*zoom/2;
            const carMaxX = vechicle.position.x + vechicleLength*zoom/2;
            if(chickenMaxX > carMinX && chickenMinX < carMaxX) {
                endDOM.style.visibility = 'visible';
            }
        });
    
    }
    renderer.render( scene, camera );    
}

requestAnimationFrame( animate );
</script>

3.nginx的主配置文件:nginx.conf

worker_processes  4;   nginx工作进程数,根据cpu的核数定义
events {
    worker_connections  1024;    #连接数
}
#http区域块,定义nginx的核心web功能
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"';
    #开启访问日志功能的参数          
    access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    #保持长连接
    keepalive_timeout  65;
    #支持图片 gif等等压缩,减少网络
    gzip  on;
    
    #这个server标签 控制着nginx的虚拟主机(web站点)
    server {
        # 定义nginx的入口端口是80端口
        listen       80;
        # 填写域名,没有域名就写ip地址
        server_name  www.s15rihan.com;
        # 定义编码
        charset utf-8;
        # location定义网页的访问url
        #就代表 用户的请求 是  192.168.13.79/
        location / {
            #root参数定义网页根目录
            root   html;
            #定义网页的首页文件,的名字的
            index  index.html index.htm;
        }
        #定义错误页面,客户端的错误,就会返回40x系列错误码
        error_page  404  403 401 400            /404.html;
        #500系列错误代表后端代码出错
        error_page   500 502 503 504  /50x.html;
    }
    #在另一个server{}的外面,写入新的虚拟主机2
    server{
        listen 80;
        server_name  www.s15oumei.com;
        location /  {
        root  /opt/myserver/oumei;      #定义虚拟主机的网页根目录
        index  index.html;
        }
    }
}

4.两个虚拟主机公用一个ip端口

在nginx.conf配置文件中

worker_processes  4;   nginx工作进程数,根据cpu的核数定义
events {
    worker_connections  1024;    #连接数
}
#http区域块,定义nginx的核心web功能
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"';
    #开启访问日志功能的参数          
    access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    #保持长连接
    keepalive_timeout  65;
    #支持图片 gif等等压缩,减少网络
    gzip  on;
    
    #这个server标签 控制着nginx的虚拟主机(web站点)
    server {
        # 定义nginx的入口端口是80端口
        listen       80;
        # 填写域名,没有域名就写ip地址
        server_name  www.s15rihan.com;
        # 定义编码
        charset utf-8;
        # location定义网页的访问url
        #就代表 用户的请求 是  192.168.13.79/
        location / {
            #root参数定义网页根目录
            root   html;
            #定义网页的首页文件,的名字的
            index  index.html index.htm;
        }
        #定义错误页面,客户端的错误,就会返回40x系列错误码
        error_page  404  403 401 400            /404.html;
        #500系列错误代表后端代码出错
        error_page   500 502 503 504  /50x.html;
    }
    #在另一个server{}的外面,写入新的虚拟主机2
    server{
        listen 80;
        server_name  www.s15oumei.com;
        location /  {
        root  /opt/myserver/oumei;      #定义虚拟主机的网页根目录
        index  index.html;
        }
    }
}

 

准备两个虚拟主机的网页根目录内容

[root@localhost myserver]# tree /opt/myserver/
    /opt/myserver/
    ├── oumei
    │   └── index.html      写入自己的内容
    └── rihan
        └── index.html      写入自己的内容 

 

修改windows本地的测试域名 C:WindowsSystem32driversetchosts文件

写入如下内容
​
192.168.177.130 www.s15rihan.com  
192.168.177.130 www.s15oumei.com  
​
    因为我们没有www.s15oumei.com 也没有  www.s15rihan.com ,因此要在本地搞一个测试域名,
    不想改dns的话,就去阿里云去买一个域名~~~~~~~~~~~~~~~~~~~~~~

5.nginx的访问日志功能

1.开启nginx.conf中的日志参数

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;

2.检查access.log的日志信息

tail -f  access.log 

6.nginx的拒绝访问功能

在nginx.conf中,添加参数

在server{}虚拟主机标签中,找到location 然后添加参数
​
        #当有人访问  192.168.13.79/  的时候 
        location / {
            #拒绝参数是 deny 
            #deny 写你想拒绝的IP地址
            #deny还支持拒绝一整个网站
            deny  192.168.13.33;
            root   /opt/myserver/rihan;
            index  index.html;
        }

7.nginx的错误页面优化

1.修改nginx.conf 中的配置参数
这个s1540x.html存在 虚拟主机定义的网页根目录下
  error_page  404              /s1540x.html;

 

8.nginx代理

1.正向代理与反向代理的理解

正向代理

  正向代理类似一个跳板机,代理访问外部资源。

举个例子:

  我是一个用户,我访问不了某网站,但是我能访问一个代理服务器,这个代理服务器呢,他能访问那个我不能访问的网站,于是我先连上代理服务器,告诉他我需要那个无法访问网站的内容,代理服务器去取回来,然后返回给我。从网站的角度,只在代理服务器来取内容的时候有一次记录,有时候并不知道是用户的请求,也隐藏了用户的资料,这取决于代理告不告诉网站。

正向代理的用途:

(1)访问原来无法访问的资源,如google
​
(2) 可以做缓存,加速访问资源
​
(3)对客户端访问授权,上网进行认证
​
(4)代理可以记录用户访问记录(上网行为管理),对外隐藏用户信息
反向代理

反向代理(Reverse Proxy)实际运行方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器对外就表现为一个服务器。

反向代理的作用:

(1)保证内网的安全,可以使用反向代理提供WAF功能,阻止web攻击

大型网站,通常将反向代理作为公网访问地址,Web服务器是内网。

(2)负载均衡,通过反向代理服务器来优化网站的负载

二者区别

2.反向代理服务器

在gninx.conf文件中添加配置

location / {
  proxy_pass http://www.baidu.com;
  #root   html;
  #index index.html index.htm;
}

浏览器 访问 192.168.177.130时 跳转到百度页面

 

9.nginx负载均衡

1.实验准备
准备三台计算机 
​
nginx1      192.168.13.121   作为nginx负载均衡器               只要我访问这个负载均衡器,查看页面的结果,到底是来自于
​
nginx2      192.168.13.24   web服务,提供一个页面        
​
nginx3      192.168.13.79  web服务,提供一个页面 
​
​
​
2.先配置两个nginx  web页面  
    192.168.13.24  准备一个   index.html  写入  你好,我是192.168.13.24机器
    192.168.13.79   准备一个    index.html 写入       老了老弟,我是192.168.13.79
    
    然后启动两个nginx web 服务
    
3.准备一个nginx负载均衡器  192.168.13.121机器上,修改nginx.conf 
写入如下内容 
            定义一个负载均衡池,负载均衡的算法有
            调度算法      概述
            轮询        按时间顺序逐一分配到不同的后端服务器(默认)
            weight       加权轮询,weight值越大,分配到的访问几率越高
            ip_hash      每个请求按访问IP的hash结果分配,这样来自同一IP的固定访问一个后端服务器
            url_hash      按照访问URL的hash结果来分配请求,是每个URL定向到同一个后端服务器
            least_conn    最少链接数,那个机器链接数少就分发
​
            1.轮询(不做配置,默认轮询)
​
            2.weight权重(优先级)
​
            3.ip_hash配置,根据客户端ip哈希分配,不能和weight一起用
​
upstream s15webserver  {
ip_hash;
server 192.168.13.79 ;
server 192.168.13.24 ;
}
 
然后在虚拟主机中添加 反向代理配置,将用户的请求,直接转发给 负载均衡池中的服务器
​
server {
        listen       80;
        #当我的请求来自于 192.168.13.121时,走这>个虚拟主机
        server_name  192.168.13.121;
​
        #charset koi8-r;
#access_log  logs/host.access.log  main;
​
        location / {
          proxy_pass http://s15webserver;
            #root   html;
            #index  index.html index.htm;
        }
​
}
​
​
4.启动负载均衡器的 nginx服务 
​
5.在客户端windows中测试访问,负载均衡器  192.168.13.121 ,查看请求分发的结果 

 

 

 

 

原文地址:https://www.cnblogs.com/shanghongyun/p/10211189.html