nginx 入门实践(Mac 篇)

本文记录了最近在 Mac 学习 nginx 的过程

嗯… 学习前端已久,经常从各种途径听说什么 nginx,之前从未接触过,感觉它好难,不过稍微看个教程入个门就感觉上手好简单,嗯… 其实就是一个配置文件?10 分钟就上手啊哈哈!

什么是 nginx ?

官网:nginx [engine x] is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server, originally written by Igor Sysoev.

nginx [engine x] 是一款轻量级的代理服务器,它可以作为 HTTP 代理服务器或反向代理,也可以作为邮件、TCP/UDP 等代理服务器。nginx 最初由 Igor Sysoev 设计。

nginx 使用场景

因为我是学习前端的... 在前端方向,个人以为 nginx 在 web 方向最常使用场景是作为前后端分离的静态资源托管和负载均衡服务器。对其在 mail/TCP/UDP 的应用并无过多了解... 学了 nginx 才知道 redis 的作用,所以赶去学习 redis 了,mail 什么的先放下...

安装 nginx 在 macOS

mac 上非常简单,敲命令:

brew install nginx # 这会同时安装 nginx 的依赖库 openssl、pcre 等
  • nginx 的配置文件目录在: /usr/local/etc/nginx ,这是 nginx 的默认配置目录,其中最主要的就是 nginx.conf 了,先随便看下。
  • nginx 的安装文件目录在: /usr/local/Cellar/nginx ,brew 把 nginx 安装到了这里,可以注意下 /nginx/html/index.html
  • 这里安装的 nginx 版本为 1.12

使用 nginx

首先,我们启动 nginx 服务:

nginx       # 启动 nginx 服务

接着访问 http://localhost:8080,就能看到 nginx 欢迎页面:

nginx 欢迎页面.png

nginx 启动成功!

此外,nginx 的常用命令也就只有下面几个:

nginx               # 启动 nginx 服务,使用默认配置:/usr/local/etc/nginx/nginx.conf
nginx -c filename   # 以此配置文件启动 nginx 服务
nginx -s stop       # 终止 nginx 服务,不保存相关信息
nginx -s quit       # 关闭 nginx 服务,保存日志等信息
nginx -s reload     # 重启 nginx 服务,改动配置文件后使用这个指令
nginx -t            # 测试配置文件是否正确,仅测试而不运行
nginx -h            # 帮助我

# 下面就不太常用了
nginx -s reopen     # 重新打开日志文件
nginx -v            # 输出 nginx 版本信息
nginx -V            # 输出 nginx 版本信息和默认配置信息
nginx -T            # 测试配置文件是否正确,同时输出文件内容,仅测试而不运行
nginx -p prefix     # 设置 prefix path (默认为: /usr/local/Cellar/nginx/1.12.2_1/)

配置 nginx

打开刚才的 /usr/local/etc/nginx/nginx.conf ,学习下 nginx 默认的配置文件(双井号是我加上的注释):


#user  nobody;                      ## 运行nginx的当前用户及用户组
worker_processes  1;                ## 启动进程数

#error_log  logs/error.log;         ## 存储错误日志,语法为 `error_log filename [error_type]`
#error_log  logs/error.log  notice; ## error_type 默认为 crit(记录最少信息),可选值为 [ debug | info | notice | warn | error | crit ]
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;         ## 记录 nginx 进程 pid


events {                            ## 包含 nginx 中所有处理连接的设置,参考 [nginx配置详解之events模块](http://blog.csdn.net/zhangsheng_1992/article/details/51689980)
    worker_connections  1024;       ## 工作进程的最大连接数
}


http {
    include       mime.types;               ## 引入 mimetypes 文件
    default_type  application/octet-stream; ## mimetypes 默认类型

    #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;                 ## 启动高效传输文件模式,[参考](http://blog.csdn.net/liuxiao723846/article/details/52634622)
    #tcp_nopush     on;                 ## 配置一次发送数据的包大小(另见:tcp_nodelay [参考](http://blog.csdn.net/liuxiao723846/article/details/52634622))

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;                          ## 启用 gzip

    server {
        listen       8080;
        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;
    #    }
    #}
    include servers/*;
}

注意配置文件中的 server { location / { root html; ...} } ,这里的 root 指定 / 路由的根目录为 html 文件夹,回想前面提到的命令:

nginx -p prefix # 设置 prefix path (默认为: /usr/local/Cellar/nginx/1.12.2_1/)

打开这里的默认路径 /usr/local/Cellar/nginx/1.12.2_1/ (注意这里 nginx 版本号可能不同),刚好有一个 html 文件夹,现在明白 nginx 的 prefix 指令了哈哈!

另外,默认的配置文件指定的 error_log 的存储位置也是相对此目录的,因此打开 error_log 时如果报错那很可能是因为 prefix 目录下没有这个文件。

反向代理与负载均衡配置

使用 nginx 做负载均衡只需两步:

  1. 配置负载均衡服务器列表 upstream
  2. 加入代理转发配置 proxy_pass

看配置文件的 http 部分:

http {
    ...
    ## 加入下面的 upstream 配置
    upstream load_balance_server {
        server  localhost:8080  weight=5;
        server  localhost:8081  weight=1;
        server  localhost:8082  weight=1;
    }
    ...
    server {
        ...
        location / {
            root   html;
            index  index.html index.htm;

            ## 加入下面的 proxy_pass 配置
            proxy_pass  http://load_balance_server;
        }
    }
    ...
}

另外,nginx 配置负载均衡默认使用轮询,上面的配置,若有 7 次访问,则分别会有 5、1、1 次命中 8080、8081、8082 端口。关于负载均衡策略参考 nginx负载均衡的5种策略(转载) - 安大叔 - 博客园

使用 nginx 做负载均衡使用了多台服务器,但每台服务器的用户 session 是不相关的,这就有个问题是用户第一次访问 A 服务器产生了 sessionA,而下一次访问可能变成了 B 服务器,B 服务器发现 session 不存在,要求重新生成 sessionB,于是产生了混乱。于是的于是,持久化 session 解决方案就出现了,比如使用独立的 redis 服务缓存 session。当然 redis 并不是持久化存储,这里的 session 持久化更是相关于服务器来说的,准确的说应该是独立于服务器的 session。因此要赶去学习 redis 啦啦啦~~~

参考:
nginx documentation
nginx中文文档
nginx负载均衡的5种策略(转载) - 安大叔 - 博客园
nginx之tcp_nopush、tcp_nodelay - CSDN博客
nginx配置详解之events模块 - CSDN博客

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,511评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,495评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,595评论 0 225
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,558评论 0 190
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,715评论 3 270
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,672评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,112评论 2 291
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,837评论 0 181
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,417评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,928评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,316评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,773评论 2 234
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,253评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,827评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,440评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,523评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,583评论 2 249

推荐阅读更多精彩内容