Nginx服务器详解

nginx服务器安装及配置文件详解

Nginx实验配置
实验1 虚拟主机
1)域名解析 文件解析
C:\Windows\System32\drivers\etc\hosts
192.168.159.251 www.sina.com
192.168.159.251 www.sohu.com
2)规划网站目录
# mkdir /home/wwwroot/sina/
# mkdir /home/wwwroot/sohu/
# vim /home/wwwroot/sina/index.html
# vim /home/wwwroot/sohu/index.html
3)修改配置文件
# vim /usr/local/nginx/conf/nginx.conf
66 listen 80;

# vim /usr/local/nginx/conf/vhost/v.conf

server {
        listen 80;
        server_name www.sina.com;
        index index.html index.htm index.php;
        root /home/wwwroot/sina;

        include enable-php.conf;

}

server {
        listen 80;
        server_name www.sohu.com;
        index index.html index.htm index.php;
        root /home/wwwroot/sohu;

        include enable-php.conf;

}

# pkill -HUP nginx

测试: www.sina.com www.sohu.com

实验2 列表页显示
配置文件加入:

# vim /usr/local/nginx/conf/nginx.conf
autoindex on;

# pkill -HUP nginx

# mv index.html a.html

测试: 192.168.159.251

实验3 rewrite 重写
www.sina.com -> www.sohu.com
1)修改配置文件
# vim /usr/local/nginx/conf/vhost/v.conf

server {
        listen 80;
        server_name www.sina.com;
        index index.html index.htm index.php;
        root /home/wwwroot/sina;
        if ($http_host = www.sina.com) {
                        rewrite  (.*)  http://www.sohu.com  permanent;
                }
        include enable-php.conf;

}

# pkill -HUP nginx

测试 www.sina.com -> www.sohu.com

网页文件跳转
# vim /usr/local/nginx/conf/vhost/v.conf

server {
        listen 80;
        server_name www.sina.com;
        index index.html index.htm index.php;
        root /home/wwwroot/sina;

        rewrite index(\d+).html /index.php?id=$1  last;

        include enable-php.conf;

}

# vim /home/wwwroot/sina/index.php

# pkill -HUP nginx

测试 www.sina.com/index6.html

实验4 反向代理 负载均衡技术
准备:客户端C windows 192.168.159.250
服务器S linux 192.168.159.251 Nginx
服务器S1 linux 192.168.159.180 Apache
服务器S2 linux 192.168.159.52 Apache

1)配置S Nginx 192.168.159.251 负责分发
修改配置文件
# vim /usr/local/nginx/conf/nginx.conf

upstream myweb1 {
        server 192.168.159.180:80;
        server 192.168.159.52:80;
}

  server {
        listen       80;
        server_name  www.sohu.com;
  location / {
        proxy_pass http://myweb1;
        proxy_next_upstream http_500 http_502 http_503 error timeout invalid_header;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
  }
}

2)登录S1 配置Apache 192.168.159.180
# ssh root@192.168.159.180
关闭虚拟主机
# vim /usr/local/apache2/htdocs/index.html
S1111111111111111111

测试: 192.168.159.180

3)登录S2 配置Apache 192.168.159.52
# ssh root@192.168.159.52
关闭虚拟主机
# vim /usr/local/apache2/htdocs/index.html
S22222222222222222222

# pkill -HUP nginx

4)测试:www.sohu.com