Nginx 是一个轻量级的 web 服务器 、反向代理服务器及电子邮件( IMAP/POP3 )代理服务器。

一、Nginx 常用指令

  1. nginx -s stop 快速关闭Nginx,可能不保存相关信息,并迅速终止web服务。
  2. nginx -s quit 平稳关闭Nginx,保存相关信息,有安排的结束web服务。
  3. nginx -s reload 因改变了Nginx相关配置,需要重新加载配置而重载。
  4. nginx -s reopen 重新打开日志文件。
  5. nginx -c filename Nginx 指定一个配置文件,来代替缺省的。
  6. nginx -t 不运行,而仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。
  7. nginx -v 显示 nginx 的版本。
  8. nginx -V 显示 nginx 的版本,编译器版本和配置参数。

二、Nginx 基本配置说明

  1. user nobody;
  2. #启动进程,通常设置成和cpu的数量相等
  3. worker_processes 1;
  4. #全局错误日志及PID文件
  5. #error_log logs/error.log;
  6. #error_log logs/error.log notice;
  7. #error_log logs/error.log info;
  8. #pid logs/nginx.pid;
  9. #工作模式及连接数上限
  10. events {
  11. #epoll是多路复用IO(I/O Multiplexing)中的一种方式,
  12. #仅用于linux2.6以上内核,可以大大提高nginx的性能
  13. use epoll;
  14. #单个后台worker process进程的最大并发链接数
  15. worker_connections 1024;
  16. # 并发总数是 worker_processes 和 worker_connections 的乘积
  17. # 即 max_clients = worker_processes * worker_connections
  18. # 在设置了反向代理的情况下,max_clients = worker_processes * worker_connections / 4 为什么
  19. # 为什么上面反向代理要除以4,应该说是一个经验值
  20. # 根据以上条件,正常情况下的Nginx Server可以应付的最大连接数为:4 * 8000 = 32000
  21. # worker_connections 值的设置跟物理内存大小有关
  22. # 因为并发受IO约束,max_clients的值须小于系统可以打开的最大文件数
  23. # 而系统可以打开的最大文件数和内存大小成正比,一般1GB内存的机器上可以打开的文件数大约是10万左右
  24. # 我们来看看360M内存的VPS可以打开的文件句柄数是多少:
  25. # $ cat /proc/sys/fs/file-max
  26. # 输出 34336
  27. # 32000 < 34336,即并发连接总数小于系统可以打开的文件句柄总数,这样就在操作系统可以承受的范围之内
  28. # 所以,worker_connections 的值需根据 worker_processes 进程数目和系统可以打开的最大文件总数进行适当地进行设置
  29. # 使得并发总数小于操作系统可以打开的最大文件数目
  30. # 其实质也就是根据主机的物理CPU和内存进行配置
  31. # 当然,理论上的并发总数可能会和实际有所偏差,因为主机还有其他的工作进程需要消耗系统资源。
  32. # ulimit -SHn 65535
  33. }
  34. http {
  35. #设定mime类型,类型由mime.type文件定义
  36. include mime.types;
  37. default_type application/octet-stream;
  38. #设定日志格式
  39. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  40. '$status $body_bytes_sent "$http_referer" '
  41. '"$http_user_agent" "$http_x_forwarded_for"';
  42. access_log logs/access.log main;
  43. # sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,
  44. # 对于普通应用,必须设为 on,
  45. # 如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,
  46. # 以平衡磁盘与网络I/O处理速度,降低系统的uptime.
  47. sendfile on;
  48. # tcp_nopush on;
  49. # 连接超时时间
  50. # keepalive_timeout 0;
  51. keepalive_timeout 65;
  52. tcp_nodelay on;
  53. # 开启gzip压缩
  54. gzip on;
  55. gzip_disable "MSIE [1-6].";
  56. # 设定请求缓冲
  57. client_header_buffer_size 128k;
  58. large_client_header_buffers 4 128k;
  59. # 设定虚拟主机配置
  60. server {
  61. # 侦听80端口
  62. listen 80;
  63. # 定义使用 www.nginx.cn访问
  64. server_name www.nginx.cn;
  65. # 定义服务器的默认网站根目录位置
  66. root html;
  67. # 设定本虚拟主机的访问日志
  68. access_log logs/nginx.access.log main;
  69. # 默认请求
  70. location / {
  71. # 定义首页索引文件的名称
  72. index index.php index.html index.htm;
  73. }
  74. # 定义错误提示页面
  75. error_page 500 502 503 504 /50x.html;
  76. location = /50x.html {
  77. }
  78. # 静态文件,nginx自己处理
  79. location ~ ^/(images|javascript|js|css|flash|media|static)/ {
  80. # 过期30天,静态文件不怎么更新,过期可以设大一点,
  81. # 如果频繁更新,则可以设置得小一点。
  82. expires 30d;
  83. }
  84. # PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
  85. location ~ .php$ {
  86. fastcgi_pass 127.0.0.1:9000;
  87. fastcgi_index index.php;
  88. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  89. include fastcgi_params;
  90. }
  91. # 禁止访问 .htxxx 文件
  92. location ~ /.ht {
  93. deny all;
  94. }
  95. }
  96. }

location 匹配规则

1、location 匹配命令

~ : 波浪线表示执行一个正则匹配,区分大小写
~* : 表示执行一个正则匹配,不区分大小写
^~ : ^~表示普通字符匹配,如果该选项匹配,只匹配该选项,不匹配别的选项,一般用来匹配目录
= : 进行普通字符精确匹配
@ : “@” 定义一个命名的 location,使用在内部定向时,例如 error_page, try_files

2、location 匹配的优先级(与location在配置文件中的顺序无关)

= : 精确匹配会第一个被处理。如果发现精确匹配,nginx停止搜索其他匹配。
普通字符匹配,正则表达式规则和长的块规则将被优先和查询匹配,也就是说如果该项匹配还需去看有没有正则表达式匹配和更长的匹配。
^~ : 则只匹配该规则,nginx停止搜索其他匹配,否则nginx会继续处理其他location指令。
最后匹配理带有”~”和”~*”的指令,如果找到相应的匹配,则nginx停止搜索其他匹配;当没有正则表达式或者没有正则表达式被匹配的情况下,那么匹配程度最高的逐字匹配指令会被使用。

3、location 优先级官方文档

  1. Directives with the = prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings, longest match first. If this match used the ^~ prefix, searching stops.
  3. Regular expressions, in order of definition in the configuration file.
  4. If #3 yielded a match, that result is used. Else the match from #2 is used.
  5. = 前缀的指令严格匹配这个查询。如果找到,停止搜索。
  6. 所有剩下的常规字符串,最长的匹配。如果这个匹配使用^〜前缀,搜索停止。
  7. 正则表达式,在配置文件中定义的顺序。
  8. 如果第3条规则产生匹配的话,结果被使用。否则,使用第2条规则的结果。

例如

  1. location = / {
  2. # 只匹配"/".
  3. [ configuration A ]
  4. }
  5. location / {
  6. # 匹配任何请求,因为所有请求都是以"/"开始
  7. # 但是更长字符匹配或者正则表达式匹配会优先匹配
  8. [ configuration B ]
  9. }
  10. location ^~ /images/ {
  11. # 匹配任何以 /images/ 开始的请求,并停止匹配 其它location
  12. [ configuration C ]
  13. }
  14. location ~* .(gif|jpg|jpeg)$ {
  15. # 匹配以 gif, jpg, or jpeg结尾的请求.
  16. # 但是所有 /images/ 目录的请求将由 [Configuration C]处理.
  17. [ configuration D ]
  18. }


请求URI例子:

  • / -> 符合configuration A
  • /documents/document.html -> 符合configuration B
  • /images/1.gif -> 符合configuration C
  • /documents/1.jpg ->符合 configuration D

@location 例子

  1. error_page 404 = @fetch;
  2. location @fetch(
  3. proxy_pass http://fetch;
  4. )

全局变量

$args : 这个变量等于请求行中的参数,同$query_string
$content_length : 请求头中的Content-length字段
$content_type : 请求头中的Content-Type字段
$document_root : 当前请求在root指令中指定的值
$host : 请求主机头字段,否则为服务器名称
$http_user_agent : 客户端agent信息
$http_cookie : 客户端cookie信息
$limit_rate : 这个变量可以限制连接速率
$$request_filename : 客户端请求的动作,通常为GETPOST
$remote_addr : 客户端的IP地址
$remote_port : 客户端的端口
$remote_user : 已经经过Auth Basic Module验证的用户名
$request_filename : 当前请求的文件路径,由rootalias指令与URI请求生成
$schemeHTTP方法(如httphttps
$server_protocol : 请求使用的协议,通常是HTTP/1.0HTTP/1.1
$server_addr : 服务器地址,在完成一次系统调用后可以确定这个值
$server_name : 服务器名称
$server_port : 请求到达服务器的端口号
$request_uri : 包含请求参数的原始URI,不包含主机名,如/foo/bar.php?arg=baz
$uri : 不带请求参数的当前URI$uri不包含主机名,如/foo/bar.html
$document_uri : 与$uri相同

假设请求为[http://www.qq.com:8080/a/b/c.php](http://www.qq.com:8080/a/b/c.php),则

  1. $hostwww.qq.com
  2. $server_port8080
  3. $request_urihttp://www.qq.com:8080/a/b/c.php
  4. $document_uri:/a/b/c.php
  5. $document_root:/var/www/html
  6. $request_filename:/var/www/html/a/b/c.php

主机名(server_name)匹配

从上到下的优先级为从高到低

  1. 明确的 server_name 名称,如 www.qq.com
  2. 前缀通配符,如 *.qq.com. qq.com
  3. 后缀通配符,如 www.qq.*
  4. 正则表达式,如 ~[a-z]+\.qq\.com

    Location查找规则

    从上到下的优先级为从高到低

  5. 等号类型,精确匹配,如 location = / {}

  6. ^~ 类型,前缀匹配,不支持正则,如 location ^~ /user {}
  7. ~~* 类型,正则匹配, ~ 区分大小写, ~* 不区分大小写,如 location ~ ^/user {}
  8. 常规字符串匹配类型,如 location / {}location /user {}

    Try_files规则

    1. try_files $uri $uri/ /index.php

    假设请求为[http://www.qq.com/test](http://www.qq.com/test),则$uritest

  9. 查找 /$root/test 文件

  10. 查找 /$root/test/ 目录
  11. 发起 /index.php 的内部”子请求”

    Rewrite规则

    1. rewrite ^/images/(.*).(png|jpg|gif)$ /images?name=$1.$4 last;
    上面的 rewrite 规则会将文件名改写到参数中

last : 相当于 Apache 的[L]标记,表示完成rewrite
break : 停止执行当前虚拟主机的后续rewrite指令集
redirect : 返回302临时重定向,地址栏会显示跳转后的地址
permanent : 返回301永久重定向,地址栏会显示跳转后的地址

三、Nginx 配置实战

我始终认为,各种开发工具的配置还是结合实战来讲述,会让人更易理解。

1、http 反向代理配置

我们先实现一个小目标:不考虑复杂的配置,仅仅是完成一个 http 反向代理。
nginx.conf 配置文件如下:

注:conf / nginx.conf 是 nginx 的默认配置文件。你也可以使用 nginx -c 指定你的配置文件

  1. # 运行用户
  2. # user somebody;
  3. # 启动进程,通常设置成和cpu的数量相等
  4. worker_processes 1;
  5. # 全局错误日志
  6. error_log D:/Tools/nginx-1.10.1/logs/error.log;
  7. error_log D:/Tools/nginx-1.10.1/logs/notice.log notice;
  8. error_log D:/Tools/nginx-1.10.1/logs/info.log info;
  9. # PID文件,记录当前启动的nginx的进程ID
  10. pid D:/Tools/nginx-1.10.1/logs/nginx.pid;
  11. # 工作模式及连接数上限
  12. events {
  13. worker_connections 1024; # 单个后台worker process进程的最大并发链接数
  14. }
  15. # 设定http服务器,利用它的反向代理功能提供负载均衡支持
  16. http {
  17. # 设定mime类型(邮件支持类型),类型由mime.types文件定义
  18. include D:/Tools/nginx-1.10.1/conf/mime.types;
  19. default_type application/octet-stream;
  20. # 设定日志
  21. log_format main '[$remote_addr] - [$remote_user] [$time_local] "$request" '
  22. '$status $body_bytes_sent "$http_referer" '
  23. '"$http_user_agent" "$http_x_forwarded_for"';
  24. access_log D:/Tools/nginx-1.10.1/logs/access.log main;
  25. rewrite_log on;
  26. # sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,
  27. # 必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
  28. sendfile on;
  29. # tcp_nopush on;
  30. # 连接超时时间
  31. keepalive_timeout 120;
  32. tcp_nodelay on;
  33. # gzip压缩开关
  34. # gzip on;
  35. #设定实际的服务器列表
  36. upstream zp_server1 {
  37. server 127.0.0.1:8089;
  38. }
  39. # HTTP服务器
  40. server {
  41. # 监听80端口,80端口是知名端口号,用于HTTP协议
  42. listen 80;
  43. # 定义使用www.xx.com访问
  44. server_name www.helloworld.com;
  45. # 首页
  46. index index.html
  47. # 指向webapp的目录
  48. root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp;
  49. # 编码格式
  50. charset utf-8;
  51. # 代理配置参数
  52. proxy_connect_timeout 180;
  53. proxy_send_timeout 180;
  54. proxy_read_timeout 180;
  55. proxy_set_header Host $host;
  56. proxy_set_header X-Forwarder-For $remote_addr;
  57. # 反向代理的路径(和upstream绑定),location 后面设置映射的路径
  58. location / {
  59. proxy_pass http://zp_server1;
  60. }
  61. # 静态文件,nginx自己处理
  62. location ~ ^/(images|javascript|js|css|flash|media|static)/ {
  63. root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp\views;
  64. # 过期30天,静态文件不怎么更新,过期可以设大一点,如果频繁更新,则可以设置得小一点。
  65. expires 30d;
  66. }
  67. # 设定查看Nginx状态的地址
  68. location /NginxStatus {
  69. stub_status on;
  70. access_log on;
  71. auth_basic "NginxStatus";
  72. auth_basic_user_file conf/htpasswd;
  73. }
  74. # 禁止访问 .htxxx 文件
  75. location ~ /\.ht {
  76. deny all;
  77. }
  78. # 错误处理页面(可选择性配置)
  79. # error_page 404 /404.html;
  80. # error_page 500 502 503 504 /50x.html;
  81. # location = /50x.html {
  82. # root html;
  83. # }
  84. }
  85. }

好了,让我们来试试吧:

  1. 启动 webapp,注意启动绑定的端口要和 nginx 中的 upstream 设置的端口保持一致。
  2. 更改 host:在 C:\Windows\System32\drivers\etc 目录下的 host 文件中添加一条 DNS 记录

    1. 127.0.0.1 www.helloworld.com
  3. 启动前文中 startup.bat 的命令

  4. 在浏览器中访问 www.helloworld.com,不出意外,已经可以访问了。

    2、负载均衡配置

    上一个例子中,代理仅仅指向一个服务器。
    但是,网站在实际运营过程中,多半都是有多台服务器运行着同样的 app,这时需要使用负载均衡来分流。
    nginx 也可以实现简单的负载均衡功能。
    假设这样一个应用场景:将应用部署在 192.168.1.11:80192.168.1.12:80192.168.1.13:80 三台 linux 环境的服务器上。网站域名叫 www.helloworld.com,公网 IP 为 192.168.1.11 。在公网 IP 所在的服务器上部署 nginx,对所有请求做负载均衡处理。
    nginx.conf 配置如下:

    1. http {
    2. #设定mime类型,类型由mime.type文件定义
    3. include /etc/nginx/mime.types;
    4. default_type application/octet-stream;
    5. #设定日志格式
    6. access_log /var/log/nginx/access.log;
    7. #设定负载均衡的服务器列表
    8. upstream load_balance_server {
    9. #weigth参数表示权值,权值越高被分配到的几率越大
    10. server 192.168.1.11:80 weight=5;
    11. server 192.168.1.12:80 weight=1;
    12. server 192.168.1.13:80 weight=6;
    13. }
    14. #HTTP服务器
    15. server {
    16. #侦听80端口
    17. listen 80;
    18. #定义使用www.xx.com访问
    19. server_name www.helloworld.com;
    20. #对所有请求进行负载均衡请求
    21. location / {
    22. #定义服务器的默认网站根目录位置
    23. root /root;
    24. #定义首页索引文件的名称
    25. index index.html index.htm;
    26. #请求转向load_balance_server 定义的服务器列表
    27. proxy_pass http://load_balance_server;
    28. # 以下是一些反向代理的配置(可选择性配置)
    29. # proxy_redirect off;
    30. proxy_set_header Host $host;
    31. proxy_set_header X-Real-IP $remote_addr;
    32. # 后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
    33. proxy_set_header X-Forwarded-For $remote_addr;
    34. # nginx跟后端服务器连接超时时间(代理连接超时)
    35. proxy_connect_timeout 90;
    36. # 后端服务器数据回传时间(代理发送超时)
    37. proxy_send_timeout 90;
    38. # 连接成功后,后端服务器响应时间(代理接收超时)
    39. proxy_read_timeout 90;
    40. # 设置代理服务器(nginx)保存用户头信息的缓冲区大小
    41. proxy_buffer_size 4k;
    42. # proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
    43. proxy_buffers 4 32k;
    44. # 高负荷下缓冲大小(proxy_buffers*2)
    45. proxy_busy_buffers_size 64k;
    46. # 设定缓存文件夹大小,大于这个值,将从upstream服务器传
    47. proxy_temp_file_write_size 64k;
    48. # 允许客户端请求的最大单文件字节数
    49. client_max_body_size 10m;
    50. # 缓冲区代理缓冲用户端请求的最大字节数
    51. client_body_buffer_size 128k;
    52. }
    53. }
    54. }

    3、网站有多个 webapp 的配置

    当一个网站功能越来越丰富时,往往需要将一些功能相对独立的模块剥离出来,独立维护。这样的话,通常,会有多个 webapp。
    举个例子:假如 www.helloworld.com 站点有好几个 webapp,finance(金融)、product(产品)、admin(用户中心)。访问这些应用的方式通过上下文(context)来进行区分:
    www.helloworld.com/finance/
    www.helloworld.com/product/
    www.helloworld.com/admin/

我们知道,http 的默认端口号是 80,如果在一台服务器上同时启动这 3 个 webapp 应用,都用 80 端口,肯定是不成的。所以,这三个应用需要分别绑定不同的端口号。
那么,问题来了,用户在实际访问 www.helloworld.com 站点时,访问不同 webapp,总不会还带着对应的端口号去访问吧。所以,你再次需要用到反向代理来做处理。
配置也不难,来看看怎么做吧:

  1. http {
  2. # 此处省略一些基本配置
  3. upstream product_server {
  4. server www.helloworld.com:8081;
  5. }
  6. upstream admin_server {
  7. server www.helloworld.com:8082;
  8. }
  9. upstream finance_server {
  10. server www.helloworld.com:8083;
  11. }
  12. server {
  13. # 此处省略一些基本配置
  14. # 默认指向product的server
  15. location / {
  16. proxy_pass http://product_server;
  17. }
  18. location /product/ {
  19. proxy_pass http://product_server;
  20. }
  21. location /admin/ {
  22. proxy_pass http://admin_server;
  23. }
  24. location /finance/ {
  25. proxy_pass http://finance_server;
  26. }
  27. }
  28. }

4、https 反向代理配置

一些对安全性要求比较高的站点,可能会使用 HTTPS(一种使用 ssl 通信标准的安全 HTTP 协议)。
这里不科普 HTTP 协议和 SSL 标准。但是,使用 nginx 配置 https 需要知道几点:
HTTPS 的固定端口号是 443,不同于 HTTP 的 80 端口 SSL 标准需要引入安全证书,所以在 nginx.conf 中你需要指定证书和它对应的 key 其他和 http 反向代理基本一样,只是在 Server 部分配置有些不同。

  1. # HTTP服务器
  2. server {
  3. # 监听443端口。443为知名端口号,主要用于HTTPS协议
  4. listen 443 ssl;
  5. # 定义使用www.xx.com访问
  6. server_name www.helloworld.com;
  7. # ssl证书文件位置(常见证书文件格式为:crt/pem)
  8. ssl_certificate cert.pem;
  9. # ssl证书key位置
  10. ssl_certificate_key cert.key;
  11. # ssl配置参数(选择性配置)
  12. ssl_session_cache shared:SSL:1m;
  13. ssl_session_timeout 5m;
  14. # 数字签名,此处使用MD5
  15. ssl_ciphers HIGH:!aNULL:!MD5;
  16. ssl_prefer_server_ciphers on;
  17. location / {
  18. root /root;
  19. index index.html index.htm;
  20. }
  21. }

5、静态站点配置

有时候,我们需要配置静态站点(即 html 文件和一堆静态资源)。
举例来说:如果所有的静态资源都放在了 /app/dist 目录下,我们只需要在 nginx.conf 中指定首页以及这个站点的 host 即可。
配置如下:

  1. worker_processes 1;
  2. events {
  3. worker_connections 1024;
  4. }
  5. http {
  6. include mime.types;
  7. default_type application/octet-stream;
  8. sendfile on;
  9. keepalive_timeout 65;
  10. gzip on;
  11. gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/javascript image/jpeg image/gif image/png;
  12. gzip_vary on;
  13. server {
  14. listen 80;
  15. server_name static.zp.cn;
  16. location / {
  17. root /app/dist;
  18. index index.html;
  19. # 转发任何请求到 index.html
  20. }
  21. }
  22. }

然后,添加 HOST:
127.0.0.1 static.zp.cn
此时,在本地浏览器访问 static.zp.cn ,就可以访问静态站点了。

6、搭建文件服务器

有时候,团队需要归档一些数据或资料,那么文件服务器必不可少。使用 Nginx 可以非常快速便捷的搭建一个简易的文件服务。
Nginx 中的配置要点:

  • 将 autoindex 开启可以显示目录,默认不开启。
  • 将 autoindex_exact_size 开启可以显示文件的大小。
  • 将 autoindex_localtime 开启可以显示文件的修改时间。
  • root 用来设置开放为文件服务的根路径。
  • charset 设置为 charset utf-8,gbk;,可以避免中文乱码问题(windows 服务器下设置后,依然乱码,本人暂时没有找到解决方法)。

一个最简化的配置如下:

  1. # 显示目录
  2. autoindex on;
  3. # 显示文件大小
  4. autoindex_exact_size on;
  5. # 显示文件时间
  6. autoindex_localtime on;
  7. server {
  8. # windows 服务器下设置后,依然乱码,暂时无解
  9. charset utf-8,gbk;
  10. listen 9050 default_server;
  11. listen [::]:9050 default_server;
  12. server_name _;
  13. root /share/fs;
  14. }

7、跨域解决方案

web 领域开发中,经常采用前后端分离模式。这种模式下,前端和后端分别是独立的 web 应用程序,例如:后端是 Java 程序,前端是 React 或 Vue 应用。
各自独立的 web app 在互相访问时,势必存在跨域问题。解决跨域问题一般有两种思路:

1. CORS

在后端服务器设置 HTTP 响应头,把你需要运行访问的域名加入加入 Access-Control-Allow-Origin 中。

2. jsonp

把后端根据请求,构造 json 数据,并返回,前端用 jsonp 跨域。

这两种思路,本文不展开讨论。
需要说明的是,nginx 根据第一种思路,也提供了一种解决跨域的解决方案。
举例:www.helloworld.com 网站是由一个前端 app ,一个后端 app 组成的。前端端口号为 9000, 后端端口号为 8080。
前端和后端如果使用 http 进行交互时,请求会被拒绝,因为存在跨域问题。来看看,nginx 是怎么解决的吧:
首先,在 enable-cors.conf 文件中设置 cors :

  1. # allow origin list
  2. set $ACAO '*';
  3. # set single origin
  4. if ($http_origin ~* (www.helloworld.com)$) {
  5. set $ACAO $http_origin;
  6. }
  7. if ($cors = "trueget") {
  8. add_header 'Access-Control-Allow-Origin' "$http_origin";
  9. add_header 'Access-Control-Allow-Credentials' 'true';
  10. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  11. add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
  12. }
  13. if ($request_method = 'OPTIONS') {
  14. set $cors "${cors}options";
  15. }
  16. if ($request_method = 'GET') {
  17. set $cors "${cors}get";
  18. }
  19. if ($request_method = 'POST') {
  20. set $cors "${cors}post";
  21. }

接下来,在你的服务器中 include enable-cors.conf 来引入跨域配置:

  1. # ----------------------------------------------------
  2. # 此文件为项目 nginx 配置片段
  3. # 可以直接在 nginx config 中 include(推荐)
  4. # 或者 copy 到现有 nginx 中,自行配置
  5. # www.helloworld.com 域名需配合 dns hosts 进行配置
  6. # 其中,api 开启了 cors,需配合本目录下另一份配置文件
  7. # ----------------------------------------------------
  8. upstream front_server{
  9. server www.helloworld.com:9000;
  10. }
  11. upstream api_server{
  12. server www.helloworld.com:8080;
  13. }
  14. server {
  15. listen 80;
  16. server_name www.helloworld.com;
  17. location ~ ^/api/ {
  18. include enable-cors.conf;
  19. proxy_pass http://api_server;
  20. rewrite "^/api/(.*)$" /$1 break;
  21. }
  22. location ~ ^/ {
  23. proxy_pass http://front_server;
  24. }
  25. }

四、查看一个实例

下面是一个 laravel框架Nginx配置的例子,听过这堂课终于了解了下面的原理。

  1. server {
  2. listen 80 default_server;
  3. listen [::]:80 default_server ipv6only=on;
  4. # 设定网站根目录
  5. root /var/www/laravel/public;
  6. # 网站默认首页
  7. index index.php index.html index.htm;
  8. # 服务器名称,server_domain_or_IP 请替换为自己设置的名称或者 IP 地址
  9. server_name server_domain_or_IP;
  10. # 修改为 Laravel 转发规则,否则PHP无法获取$_GET信息,提示404错误
  11. location / {
  12. try_files $uri $uri/ /index.php?$query_string;
  13. }
  14. # PHP 支持
  15. location ~ \.php$ {
  16. try_files $uri /index.php =404;
  17. fastcgi_split_path_info ^(.+\.php)(/.+)$;
  18. fastcgi_pass unix:/var/run/php5-fpm.sock;
  19. fastcgi_index index.php;
  20. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  21. include fastcgi_params;
  22. }
  23. }

我们主要关注两个location,假设地址是[http://www.qq.com/user/info](http://www.qq.com/user/info),会匹配到如下location

  1. location / {
  2. try_files $uri $uri/ /index.php?$query_string;
  3. }

由于$uri$uri/是不存在的,所以会走/index.php?$query_string,这时候会发起一个内部“子请求”,“子请求”会重新匹配location,然后匹配到如下location

  1. location ~ \.php$ {
  2. try_files $uri /index.php =404;
  3. fastcgi_split_path_info ^(.+\.php)(/.+)$;
  4. fastcgi_pass unix:/var/run/php5-fpm.sock;
  5. fastcgi_index index.php;
  6. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  7. include fastcgi_params;
  8. }

这样请求就会发送到fastcgi去做处理。