专栏名称: SegmentFault思否
SegmentFault (www.sf.gg)开发者社区,是中国年轻开发者喜爱的极客社区,我们为开发者提供最纯粹的技术交流和分享平台。
目录
相关文章推荐
码农翻身  ·  中国的大模型怎么突然间就领先了? ·  15 小时前  
程序员小灰  ·  3个令人惊艳的DeepSeek项目,诞生了! ·  2 天前  
OSC开源社区  ·  2024: 大模型背景下知识图谱的理性回归 ·  4 天前  
程序猿  ·  “未来 3 年内,Python 在 AI ... ·  5 天前  
程序员小灰  ·  DeepSeek做AI代写,彻底爆了! ·  5 天前  
51好读  ›  专栏  ›  SegmentFault思否

前端 Nginx 使用札记

SegmentFault思否  · 公众号  · 程序员  · 2018-03-27 08:00

正文

nginx是什么?

nginx是俄罗斯人 Igor Sysoev为俄罗斯访问量第二的Rambler.ru站点开发的一个十分轻量级的HTTP服务器。它是一个高性能的HTTP和反向代理服务器,同时也可以作为IMAP/POP3/SMTP的代理服务器。nginx使用的是BSD许可。

Nginx 以事件驱动的方式编写,所以有非常好的性能,同时也是一个非常高效的反向代理、负载平衡。

Nginx 因为它的稳定性、丰富的模块库、灵活的配置和低系统资源的消耗而闻名。

nginx适合用来做mongrel clusters 的前端 HTTP 响应。

为什么要用nginx,nginx有什么特点?

nginx的特点(https://www.ctolib.com/topics-101000.html):

  • 核心特点:高并发请求的同时保持高效的服务

  • 热部署

  • 低内存消耗

  • 处理响应请求很快

  • 具有很高的可靠性

同时,nginx也可以实现高效的反向代理、负载均衡。

前端可以用nginx做些什么?

  • 搭建静态资源服务器

  • 反向代理分发后端服务(可以和nodejs搭配实现前后端分离)和跨域问题

  • 根据User Agent来重定向站点

  • 开发环境或测试环境切换(切换host)

  • url重写,使用rewrie规则本地映射

  • 资源内容篡改

  • 获取cookie做分流

  • 资源合并

  • gzip压缩

  • 压缩图片

  • sourceMap调试

如何安装nginx?

mac安装:

安装brew之后,执行命令:

  1. $ sudo brew install nginx

windows安装
  1. 下载: nginx官网

  2. 解压运行:解压至 c : \nginx ,运行 nginx . exe (即 nginx - c conf\nginx . conf ),默认使用80端口,日志见文件夹 C : \nginx\logs

  3. 关闭: nginx - s stop taskkill / F / IM nginx . exe > nul

注:以下皆以mac为例。

nginx如何启动、重启、关闭?

查看nginx版本: nginx - v

启动nginx服务:

  • 方法一:运行命令: sudo brew services start nginx

  • 方法二:运行命令: nginx

访问http://localhost:8080,出现如下界面则表示安装成功:

关闭nginx服务:

  • 方法一:运行命令: sudo brew services stop nginx

  • 方法二:运行命令: nginx - s stop

  • 方法三:

    • 运行命令: ps - ef | grep nginx ,找到master对应的进程号。

    • 快速停止: kill - TERM nginx 进程号 kill - INT nginx 进程号

    • 从容停止: kill - QUIT nginx 进程号

    • 强制停止所有nginx进程: pkill - 9 nginx

重启nginx服务:

  • 方法一: nginx - s reload

  • 方法二: 平滑重启命令: kill - HUP nginx 进程号

nginx信号控制:

  • TERM , INT 快速关闭

  • QUIT 从容关闭

  • HUP 平滑重启,重新加载配置文件

  • USR1 重新打开日志文件,在切割日志时用途较大

  • USR2 平滑升级可执行程序

  • WINCH 从容关闭工作进程

如何查看nginx的配置文件nginx.conf的路径和安装路径?

查看配置文件位置和测试配置文件语法:运行命令 nginx - t :

查看nginx安装路径:因为是使用brew安装的,所以使用brew命令: brew info nginx

nginx.conf基本配置有哪些?

nginx配置文件主要分成四个部分:

  • main,全局设置,影响其它部分所有设置

  • server,主机服务相关设置,主要用于指定虚拟主机域名、IP和端口

  • location,URL匹配特定位置后的设置,反向代理、内容篡改相关设置

  • upstream,上游服务器设置,负载均衡相关配置

他们之间的关系式:server继承main,location继承server;upstream既不会继承指令也不会被继承。

如下是一份通用的配置和详解:

  1. #定义 Nginx 运行的用户和用户组,默认由 nobody 账号运行, windows 下面可以注释掉。

  2. user  nobody;

  3. #nginx进程数,建议设置为等于CPU总核心数。可以和worker_cpu_affinity配合

  4. worker_processes  1;

  5. #全局错误日志定义类型,[ debug | info | notice | warn | error | crit ]

  6. #error_log  logs/error.log;

  7. #error_log  logs/error.log  notice;

  8. #error_log  logs/error.log  info;

  9. #进程文件,window下可以注释掉

  10. #pid        logs/nginx.pid;

  11. # 一个nginx进程打开的最多文件描述符(句柄)数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,

  12. # 但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。

  13. worker_rlimit_nofile 65535;

  14. #工作模式与连接数上限

  15. events {

  16.    # 参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ];

  17.    # epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。

  18.   #use epoll;

  19.   #connections 20000;  # 每个进程允许的最多连接数

  20.   # 单个进程最大连接数(最大连接数=连接数*进程数)该值受系统进程最大打开文件数限制,需要使用命令ulimit -n 查看当前设置

  21.   worker_connections 65535;

  22. }

  23. #设定http服务器

  24. http {

  25.    #文件扩展名与文件类型映射表

  26.    #include 是个主模块指令,可以将配置文件拆分并引用,可以减少主配置文件的复杂度

  27.    include       mime.types;

  28.    #默认文件类型

  29.    default_type  application/octet-stream;

  30.    #charset utf-8; #默认编码

  31.    #定义虚拟主机日志的格式

  32.    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '

  33.    #                  '$status $body_bytes_sent "$http_referer" '

  34.    #                  '"$http_user_agent" "$http_x_forwarded_for"';

  35.    #定义虚拟主机访问日志

  36.    #access_log  logs/access.log  main;

  37.    #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。

  38.    sendfile        on;

  39.     #autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。

  40.    #防止网络阻塞

  41.    #tcp_nopush     on;

  42.    #长连接超时时间,单位是秒,默认为0

  43.    keepalive_timeout  65;

  44.    # gzip压缩功能设置

  45.    gzip on; #开启gzip压缩输出

  46.    gzip_min_length 1k; #最小压缩文件大小

  47.    gzip_buffers    4 16k; #压缩缓冲区

  48.    gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)

  49.    gzip_comp_level 6; #压缩等级

  50.    #压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。

  51.    gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/ xml;

  52.    gzip_vary on; //和http头有关系,加个vary头,给代理服务器用的,有的浏览器支持压缩,有的不支持,所以避免浪费不支持的也压缩,所以根据客户端的HTTP头来判断,是否需要压缩

  53.    #limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用

  54.    # http_proxy服务全局设置

  55.    client_max_body_size   10m;

  56.    client_body_buffer_size   128k;

  57.    proxy_connect_timeout   75;

  58.    proxy_send_timeout   75;

  59.    proxy_read_timeout   75;

  60.    proxy_buffer_size   4k;

  61.    proxy_buffers   4 32k;

  62.    proxy_busy_buffers_size   64k;

  63.    proxy_temp_file_write_size  64k;

  64.    proxy_temp_path   /usr/local/nginx/proxy_temp 1 2;

  65.   # 设定负载均衡后台服务器列表

  66.    upstream  backend .com  {

  67.        #ip_hash; # 指定支持的调度算法

  68.        # upstream 的负载均衡,weight 是权重,可以根据机器配置定义权重。weigth 参数表示权值,权值越高被分配到的几率越大。

  69.        server   192.168.10.100:8080 max_fails=2 fail_timeout=30s ;  

  70.        server   192.168.10.101:8080 max_fails=2 fail_timeout=30s ;  

  71.    }

  72.    #虚拟主机的配置

  73.    server {

  74.        #监听端口

  75.        listen       80;

  76.        #域名可以有多个,用空格隔开

  77.        server_name  localhost fontend.com;

  78.        # Server Side Include,通常称为服务器端嵌入

  79.        #ssi on;

  80.         #默认编码

  81.        #charset utf-8;

  82.        #定义本虚拟主机的访问日志

  83.        #access_log  logs/host.access.log  main;

  84.        # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求

  85.        location / {

  86.            root   html;

  87.            index  index.html index.htm;

  88.        }

  89.        #error_page  404              /404.html;

  90.        # redirect server error pages to the static page /50x.html

  91.        #

  92.        error_page   500 502 503 504  /50x.html;

  93.        location = /50x.html {

  94.            root   html ;

  95.        }

  96.       # 图片缓存时间设置

  97.       location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {

  98.          expires 10d;

  99.       }

  100.       # JS和CSS缓存时间设置

  101.       location ~ .*.(js|css)?$ {

  102.          expires 1h;

  103.       }

  104.        #代理配置

  105.        # proxy the PHP scripts to Apache listening on 127.0.0.1:80

  106.        #location /proxy/ {

  107.        #    proxy_pass   http://127.0.0.1;

  108.         #}

  109.        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

  110.        #

  111.        #location ~ \.php$ {

  112.        #    root           html;

  113.        #    fastcgi_pass   127.0.0.1:9000;

  114.        #    fastcgi_index  index.php;

  115.        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

  116.        #    include        fastcgi_params;

  117.        #}

  118.        # deny access to .htaccess files, if Apache's document root

  119.        # concurs with nginx's one

  120.        #

  121.        #location ~ /\.ht {

  122.        #    deny  all;

  123.        #}

  124.    }

  125.    # another virtual host using mix of IP-, name-, and port-based configuration

  126.    #

  127.    #server {

  128.    #    listen       8000;

  129.    #    listen       somename:8080;

  130.    #    server_name  somename  alias  another.alias;

  131.    #    location / {

  132.    #        root   html;

  133.    #        index  index.html index.htm;

  134.    #    }

  135.    #}

  136.    # HTTPS server

  137.    #

  138.    #server {

  139.    #    listen       443 ssl;

  140.    #    server_name  localhost;

  141.    #    ssl_certificate      cert.pem;

  142.    #    ssl_certificate_key  cert.key;

  143.    #    ssl_session_cache    shared:SSL:1m;

  144.     #    ssl_session_timeout  5m;

  145.    #    ssl_ciphers  HIGH:!aNULL:!MD5;

  146.    #    ssl_prefer_server_ciphers  on;

  147.    #    location / {

  148.    #        root   html;

  149.    #        index  index.html index.htm;

  150.    #    }

  151.    #}

  152. }

location如何匹配?

示例:

  1. location  = / {

  2.  # 精确匹配 / ,主机名后面不能带任何字符串

  3.  [ configuration A ]

  4. }

  5. location  / {

  6.  # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求

  7.  # 但是正则和最长字符串会优先匹配

  8.  [ configuration B ]

  9. }

  10. location /documents/ {

  11.  # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索

  12.  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条

  13.  [ configuration C ]

  14. }

  15. location ~ /documents/Abc {

  16.  # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索

  17.  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条

  18.  [ configuration CC ]

  19. }

  20. location ^~ /images/ {

  21.  # 匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条。

  22.  [ configuration D ]

  23. }

  24. location ~* \.(gif|jpg|jpeg)$ {

  25.  # 匹配所有以 gif,jpg或jpeg 结尾的请求

  26.  # 然而,所有请求 /images/ 下的图片会被 config D 处理,因为 ^~ 到达不了这一条正则

  27.  [ configuration E ]

  28. }

  29. location /images/ {

  30.  # 字符匹配到 /images/,继续往下,会发现 ^~ 存在

  31.  [ configuration F ]

  32. }

  33. location /images/abc {

  34.  # 最长字符匹配到 /images/abc,继续往下,会发现 ^~ 存在

  35.  # F与G的放置顺序是没有关系的

  36.  [ configuration G ]

  37. }

  38. location ~ /images/abc/ {

  39.  # 只有去掉 config D 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用

  40.    [ configuration H ]

  41. }

  42. location ~* /js/.*/\.js

说明:

  • = 开头表示精确匹配

  • ^~ 开头表示uri以某个常规字符串开头,不是正则匹配

  • ~ 开头表示区分大小写的正则匹配;

  • ~* 开头表示不区分大小写的正则匹配

  • / 通用匹配, 如果没有其它匹配,任何请求都会匹配到

优先级:

(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)

如何配置反向代理?

详解:

  1. # 对 “/” 启用反向代理

  2. location / {

  3.  proxy_pass http://127.0.0.1:3000;  # 设置要代理的 uri,注意最后的 /。可以是 Unix 域套接字路径,也可以是正则表达式。

  4.  proxy_redirect off; # 设置后端服务器“Location”响应头和“Refresh”响应头的替换文本

  5.  proxy_set_header X-Real-IP $remote_addr; # 获取用户的真实 IP 地址

  6.  #后端的Web服务器可以通过 X-Forwarded-For 获取用户真实IP,多个 nginx 反代的情况下,例如 CDN。参见:http://gong1208.iteye.com/blog/1559835 和 http://bbs.linuxtone.org/thread-9050-1-1.html

  7.  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

  8.  #以下是一些反向代理的配置,可选。

  9.  proxy_set_header Host $host; # 允许重新定义或者添加发往后端服务器的请求头。

  10.  client_max_body_size 10m; #允许客户端请求的最大单文件字节数

  11.  client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,

  12.  proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)

  13.  proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)

  14.  proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)

  15.  proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小

  16.  proxy_buffers 4







请到「今天看啥」查看全文