nginx 基础+进阶

nginx 教程

更新日志:
20170818 更新yum安装 和 多前端部署80端口
[toc]

nginx(基础)

准备环境 centos 6.8

yum 安装(简单速度快)

nginx 下载:https://nginx.org/en/download.html

选择编译好的版本,通过源安装。

RHEL/CentOS:

vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/
gpgcheck=0
enabled=1

但是需要修改一下 OS 和 OSRELEASE,根据实际情况修改后的,我是 centos6的如下:

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/$basearch/
gpgcheck=0
enabled=1

查看 yum 的 nginx 版本:

[root@host ~]# yum list |grep nginx
nginx.x86_64                                1.12.1-1.el6.ngx            @nginx
nginx-debug.x86_64                          1.8.0-1.el6.ngx             nginx
nginx-debuginfo.x86_64                      1.12.1-1.el6.ngx            nginx
nginx-module-geoip.x86_64                   1.12.1-1.el6.ngx            nginx
nginx-module-geoip-debuginfo.x86_64         1.12.1-1.el6.ngx            nginx
nginx-module-image-filter.x86_64            1.12.1-1.el6.ngx            nginx
nginx-module-image-filter-debuginfo.x86_64  1.12.1-1.el6.ngx            nginx
nginx-module-njs.x86_64                     1.12.1.0.1.10-1.el6.ngx     nginx
nginx-module-njs-debuginfo.x86_64           1.12.1.0.1.10-1.el6.ngx     nginx
nginx-module-perl.x86_64                    1.12.1-1.el6.ngx            nginx
nginx-module-perl-debuginfo.x86_64          1.12.1-1.el6.ngx            nginx
nginx-module-xslt.x86_64                    1.12.1-1.el6.ngx            nginx
nginx-module-xslt-debuginfo.x86_64          1.12.1-1.el6.ngx            nginx
nginx-nr-agent.noarch                       2.0.0-12.el6.ngx            nginx
pcp-pmda-nginx.x86_64                       3.10.9-9.el6                base

其他os 版本可以查看https://nginx.org/en/linux_packages.html#stable

安装

yum -y install nginx

查看 nginx 的安装目录:

[root@host ~]# rpm -ql nginx
/etc/logrotate.d/nginx
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/fastcgi_params
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/nginx.conf
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
/etc/nginx/win-utf
/etc/rc.d/init.d/nginx
/etc/rc.d/init.d/nginx-debug
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/sbin/nginx
/usr/sbin/nginx-debug
/usr/share/doc/nginx-1.12.1
/usr/share/doc/nginx-1.12.1/COPYRIGHT
/usr/share/man/man8/nginx.8.gz
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
/var/cache/nginx
/var/log/nginx


多前端项目配置
server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /tz {
        if (-d $request_filename) {
          rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
        }
        alias  /usr/local/ServerStatus/web/;
        index  index.html index.htm;
    }
。。。
。。。
拦截指定请求:
location /tz {
   if (-d $request_filename) {
     rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
   }
   alias  /usr/local/ServerStatus/web/;
   index  index.html index.htm;
}

location /tz 会拦截/tz/tz/,如果 location /tz/ 只会拦截/tz/
使用正则表达式也行。

访问路径最后的斜线问题:
if (-d $request_filename) {
    rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}

是自动在请求地址后面加上 /,例如:http://inke.cf/tz 变为 http://inke.cf/tz/,如果有端口号的话(端口不是80),需要改为下面的代码:

if (-d $request_filename) {
    rewrite ^/(.*)([^/])$ http://$http_host/$1$2/ permanent;
}

总计解决方案:
直接在nginx.conf中修改

optimize_server_names off;#优化服务器名称:关 (默认开启)
server_name_in_redirect off;#服务器名称重定向:关(默认开启)



源码编译方式安装(复杂时间长)

下载nginx:官方网站
使用的最新版本是1.12.0版本。

安装gcc

需要安装gcc的环境。

yum install gcc-c++

第三方的开发包。

PCRE

PCRE(Perl Compatible Regular Expressions)是一个Perl库,包括 perl 兼容的正则表达式库。nginx的http模块使用pcre来解析正则表达式,所以需要在linux上安装pcre库。

yum install -y pcre pcre-devel

注:pcre-devel是使用pcre开发的一个二次开发库。nginx也需要此库。

zlib

zlib库提供了很多种压缩和解压缩的方式,nginx使用zlib对http包的内容进行gzip,所以需要在linux上安装zlib库。

yum install -y zlib zlib-devel
openssl

OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用。

nginx不仅支持http协议,还支持https(即在ssl协议上传输http),所以需要在linux安装openssl库。

yum install -y openssl openssl-devel

一次性安装所有环境:

yum -y install gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel



安装步骤

会执行以下指令:

第一步:源码上传

把nginx的源码包上传到linux系统,或者直接使用linux系统下载 nginx 的源码包。

第二步:解压缩
tar zxf nginx-1.12.0.tar.gz
第三步:使用configure命令创建一makeFile文件。

进入文件目录:

cd nginx-1.12.0

复制一下内容到终端上,执行以下命令:

./configure \
--prefix=/usr/local/nginx \
--pid-path=/var/run/nginx/nginx.pid \
--lock-path=/var/lock/nginx.lock \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/temp/nginx/client \
--http-proxy-temp-path=/var/temp/nginx/proxy \
--http-fastcgi-temp-path=/var/temp/nginx/fastcgi \
--http-uwsgi-temp-path=/var/temp/nginx/uwsgi \
--http-scgi-temp-path=/var/temp/nginx/scgi
注意:

启动nginx之前,上边将临时文件目录指定为/var/temp/nginx,需要在/var下创建temp及nginx目录

mkdir /var/temp/nginx/client -p
第四步:make
make
第五步:make install
make install

因为上面指定了安装位置:/usr/local/nginx,所以进入到改目录下,可以看到安装后的一些文件。



使用技巧

启动nginx

进入sbin目录

cd /usr/local/nginx/sbin
./nginx

可以查询下是否启动ps aux|grep nginx,也可以直接访问80端口的 ip。

注意:是否关闭防火墙

关闭nginx:

./nginx -s stop

推荐使用:

./nginx -s quit

重启nginx:

先关闭后启动,会刷新配置文件:

./nginx -s reload

配置虚拟主机

就是在一台服务器启动多个网站。

  • 如何区分不同的网站:
    • 域名不同
    • 端口不同

通过端口区分不同虚拟机

Nginx的配置文件:/usr/local/nginx/conf/nginx.conf
文件内容:

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


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"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
配置一个虚拟主机

一个server节点就是一个虚拟主机(默认有一个80端口的,nginx 的介绍页)

server {
   listen       80;
   server_name  localhost;

   #charset koi8-r;

   #access_log  logs/host.access.log  main;

   location / {
       root   html; # Html是nginx安装目录下的html目录
       index  index.html index.htm; # html目录下的几个 html 文件
   }
}
配置多个虚拟主机

可以配置多个server,配置了多个虚拟主机。

...

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   html;
        index  index.html index.htm;
    }
}
server {
    listen       81;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   html-81;
        index  index.html index.htm;
    }
}

...

通过域名区分虚拟主机

域名是什么?
例如:

www.baidu.com
www.taobao.com
www.jd.com

一级域名:

baidu.com
taobao.com
jd.com

二级域名:

www.baidu.com
Image.baidu.com
Item.baidu.com

三级域名:

Image.baidu.com
Aaa.image.baidu.com

Dns服务器:把域名解析为ip地址。保存的就是域名和ip的映射关系。

注意:

一个域名对应一个ip地址,一个ip地址可以被多个域名绑定。

配置多个虚拟主机
server {
    listen       80;
    server_name  www.taobao.com;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   html-taobao;
        index  index.html index.htm;
    }
}
server {
    listen       80;
    server_name  www.baidu.com;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   html-baidu;
        index  index.html index.htm;
    }
}
本地测试

可以修改hosts文件,修改window的hosts文件:(C:\Windows\System32\drivers\etc)
可以配置域名和ip的映射关系,如果hosts文件中配置了域名和ip的对应关系,不需要走dns服务器。

域名的配置:ip 是自己服务器的 ip或虚拟机的 ip
192.168.18.130 www.taobao.com
192.168.18.130 www.baidu.com

通过访问路径区分不同目录(未实际测试,待验证)

相同 ip 相同 port 配置多前端

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

    #匹配:本地后台请求 ip
    upstream redwood_server{
        server 127.0.0.1:8080;
    }

    #imooc:sell后台请求 ip
    upstream sell_server{
        server 127.0.0.1:8080;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        #匹配:设置变量redwood 指向 匹配前端项目路径
        set $redwoodUI /Users/inke/ws/javaee/redwood/src/;

        #imooc:sell 前端项目路径
        set $sellUI /Users/inke/ws/javaee/imooc/sell_html/;

        # 访问根路径,那么会访问 nginx welcome 界面
        location / {
            root   html;
            index  index.html index.htm;
        }

        #匹配:前端 index 界面
        location /redwoodUI {
            if (-d $request_filename) {
                rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
            }
            alias   $redwoodUI;
            index  index.html index.htm;
        }

        #imooc:sell index 界面
        location /sellUI {
            if (-d $request_filename) {
                rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
            }
            alias   $sellUI;
            index  index.html index.htm;
        }

        #匹配:反向代理
        location /auth{
            proxy_pass http://redwood_server$request_uri;
        }

        #imooc:sell 反向代理
        location /sell{
            proxy_pass http://sell_server$request_uri;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

    include servers/*;
}



Mac 安装教程

准备环境

MacOS Sierra 10.12.5

安装指令:

brew install nginx

安装日志:

==> Installing dependencies for nginx: pcre, openssl@1.1
==> Installing nginx dependency: pcre
==> Downloading https://homebrew.bintray.com/bottles/pcre-8.40.sierra.bottle.tar
######################################################################## 100.0%
==> Pouring pcre-8.40.sierra.bottle.tar.gz
==> Using the sandbox
��  /usr/local/Cellar/pcre/8.40: 204 files, 5.4MB
==> Installing nginx dependency: openssl@1.1
==> Downloading https://homebrew.bintray.com/bottles/openssl@1.1-1.1.0f.sierra.b
######################################################################## 100.0%
==> Pouring openssl@1.1-1.1.0f.sierra.bottle.tar.gz
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl@1.1/certs

and run
  /usr/local/opt/openssl@1.1/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local,
because this is an alternate version of another formula.

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> ~/.zshrc

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/openssl@1.1/lib
    CPPFLAGS: -I/usr/local/opt/openssl@1.1/include

==> Summary
��  /usr/local/Cellar/openssl@1.1/1.1.0f: 6,421 files, 15.5MB
==> Installing nginx
==> Downloading https://homebrew.bintray.com/bottles/nginx-1.12.0_1.sierra.bottl
######################################################################## 100.0%
==> Pouring nginx-1.12.0_1.sierra.bottle.tar.gz
==> Caveats
Docroot is: /usr/local/var/www

The default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that
nginx can run without sudo.

nginx will load all files in /usr/local/etc/nginx/servers/.

To have launchd start nginx now and restart at login:
  brew services start nginx
Or, if you don't want/need a background service you can just run:
  nginx
==> Summary
��  /usr/local/Cellar/nginx/1.12.0_1: 23 files, 1MB

前台启动:

brew services start nginx

后台运行:

nginx

可以查询下是否启动ps aux|grep nginx,也可以直接访问80端口的 ip。

停止:

nginx -s stop

重启:

nginx -s reload

默认安装位置,修改配置可以在这里修改:

/usr/local/etc/nginx



nginx 反向代理(进阶)

正向代理(针对的是客户端方面):

反向代理(针对的是服务端方面):

反向代理服务器决定哪台服务器提供服务,反向代理服务器不提供服务,也是请求的转发。


Nginx实现反向代理

两个域名指向同一台nginx服务器,用户访问不同的域名显示不同的网页内容。
两个域名是www.sian.com.cnwww.sohu.com
nginx服务器使用虚拟机192.168.18.130

第一步:安装两个tomcat,分别运行在8080和8081端口。

第二步:启动两个tomcat。

第三步:反向代理服务器的配置

...

upstream tomcat1 {
    server 192.168.18.130:8080;
}

server {
    listen       80;
    server_name  www.sina.com.cn;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        proxy_pass   http://tomcat1;
        index  index.html index.htm;
    }
}

upstream tomcat2 {
    server 192.168.18.130:8081;
}

server {
    listen       80;
    server_name  www.sohu.com;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        proxy_pass   http://tomcat2;
        index  index.html index.htm;
    }
}

...

proxy_pass指定转发的网址:http://tomcat2;
upstream tomcat2是配置指定的访问 ip 和 port。
如果是服务器集群,那么直接在upstream的内部直接增加 server 即可。

服务器集群配置多个虚拟主机

例如:

upstream tomcat2 {
    server 192.168.18.130:8081;
    server 192.168.18.131:8080;
    server 192.168.18.132:80;
    server 192.168.18.133:80;
    server 192.168.18.134:80;
}

server {
    listen       80;
    server_name  www.sohu.com;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        proxy_pass   http://tomcat2;
        index  index.html index.htm;
    }
}

第四步:nginx重新加载配置文件

先关闭后启动,会刷新配置文件:

./nginx -s reload

第五步:配置域名

在hosts文件中添加域名和ip的映射关系
192.168.18.130 www.sina.com.cn
192.168.18.130 www.sohu.com



负载均衡

如果一个服务由多条服务器提供,需要把负载分配到不同的服务器处理,需要负载均衡。

upstream tomcat2 {
    server 192.168.25.148:8081;
    server 192.168.25.148:8082;
}

可以根据服务器的实际情况调整服务器权重。
权重越高分配的请求越多,权重越低,请求越少。默认是都是1

upstream tomcat2 {
    server 192.168.25.148:8081;
    server 192.168.25.148:8082 weight=2;
}

Nginx的高可用(了解,运维工作)

要实现nginx的高可用,需要实现备份机。

什么是负载均衡高可用

nginx作为负载均衡器,所有请求都到了nginx,如果nginx服务器宕机后端web服务将无法提供服务,影响严重。
为了屏蔽负载均衡服务器的宕机,需要建立一个备份机。
主服务器和备份机上都运行高可用(High Availability)监控程序,通过传送“心跳信息”来监控对方的运行状况。
当备份机不能在一定的时间内收到这样的信息时,它就接管主服务器的服务IP并继续提供负载均衡服务;
当备份管理器又从主管理器收到“心跳信息”时,它就释放服务IP地址,这样的主服务器就开始再次提供负载均衡服务。

keepalived+nginx实现主备

keepalived是集群管理中保证集群高可用的一个服务软件,用来防止单点故障。

如果超过5W并发,那么就需要花钱买硬件负载均衡了,硬件负载均衡+keepalived+nginx
如果没钱那么也可以使用 lvs ,可以达到50% 的硬件负载均衡的性能,组成 lvs+keepalived+nginx



参考:

https://www.geekzu.cn/archives/nginx-directory.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值