nginx与apache组合使用
2012-06-07 10:51:24 阿炯

本站赞助商链接,请多关照。 Nginx的并发很好,但处理动态文件需要借助于第三方系统,Apache能很好处理动态页面但并发能力欠佳。因此将两者结合起来,让nginx做为前端,将对动态页面的请求发送到后端的apache来处理,这样可在并发处理和动态解析上达到一种平衡。
相关软件的安装过程略。

Nginx主配置文件内容参考如下:
worker_processes  1;
worker_rlimit_nofile  65535;
events {
  worker_connections  65535;
  use epoll;
}
error_log  /var/log/nginx/error.log info;
http {
  include    mime.types;
  default_type  application/octet-stream;
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout  60;
  gzip on;
  gzip_http_version 1.0;
  gzip_min_length  1100;
  gzip_comp_level  3;
  gzip_buffers  4 32k;
  gzip_types    text/plain text/xml text/css application/x-javascript application/xml application/xml+rss text/javascript application/atom+xml;
  ignore_invalid_headers on;
  client_header_timeout  3m;
  client_body_timeout 3m;
  send_timeout     3m;
  connection_pool_size  256;
  server_names_hash_max_size 2048;
  server_names_hash_bucket_size 256;
  client_header_buffer_size 256k;
  large_client_header_buffers 4 256k;
  request_pool_size  32k;
  output_buffers   4 64k;
  postpone_output  1460;
  open_file_cache max=1000 inactive=300s;
  open_file_cache_valid    600s;
  open_file_cache_min_uses 2;
  open_file_cache_errors   off;
  include "/etc/nginx/conf.d/vhosts/*.conf";
  server {
    listen 80;
    server_name _;
    access_log off;
    location ~* \.(ftpquota|htaccess|asp|aspx|jsp|asa|mdb)\$ {
    deny  all;
  }
  location / {
    client_max_body_size    100m;
    client_body_buffer_size 128k;
    proxy_send_timeout   300;
    proxy_read_timeout   300;
    proxy_buffer_size    4k;
    proxy_buffers     16 32k;
    proxy_busy_buffers_size 64k;
    proxy_temp_file_write_size 64k;
    proxy_connect_timeout 30s;
    proxy_pass http://127.0.0.1:81/;
    proxy_set_header   Host   $host;
    proxy_set_header   X-Real-IP  $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  }

}

日志记录ip地址的问题
让 Nginx 跑在前方处理静态文件,然后通过 proxy 把动态请求过滤给 apache。这么有个问题,跑在后方 apache 上的应用获取到的IP都是Nginx所在服务器的IP,或者是本机 127.0.0.1。最明显就是查看 apache 的访问日志,就会见到来来去去都是内网的IP。

如果你的应用有诸如,“单个IP不能重复登陆”,“单个IP注册相隔n分钟”… 之类用于IP判别的安全规则。这么就麻烦了…. 

nginx.conf 
proxy_set_header Host $host; 
proxy_set_header X-Real-IP $remote_addr; 
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
其实这个proxy.conf里面默认都有,在nginx.conf使用include proxy.conf就可以。 

apache第三方的mod
主页:http://stderr.net/apache/rpaf/ 
下载:http://stderr.net/apache/rpaf/download/ 
安装: 
# wget http://stderr.net/apache/rpaf/download/mod_rpaf-0.6.tar.gz 
# tar zxvf mod_rpaf-0.6.tar.gz 
# cd mod_rpaf-0.6 
#/usr/local/apache2/bin/apxs -i -a -c mod_rpaf.c  //Apache 1.3.x 的安装方式 
#/usr/local/apache2/bin/apxs -i -c -n mod_rpaf-2.0.so mod_rpaf-2.0.c  //Apache 2.x 的安装方式 

httpd.conf配置: 
LoadModule rpaf_module modules/mod_rpaf-2.0.so 
RPAFenable On 
RPAFsethostname On 
RPAFproxy_ips 127.0.0.1 192.168.10.2    # 填写Nginx所在的内网IP。 
RPAFheader X-Forwarded-For 

增加Apache2和Nginx的header长度限制
nginx默认的header长度上限是4k,如果超过了这个值 
nginx会直接返回400错误 
[error] 16613#0: *105 upstream sent too big header while reading response header from upstream 

可以通过以下2个参数来调整header上限 
client_header_buffer_size 16k; 
large_client_header_buffers 4 16k; 

看起来是,nginx默认会用client_header_buffer_size这个buffer来读取header值,如果header过大,它会使用large_client_header_buffers来读取。

client_header_buffer_size 
syntax: client_header_buffer_size size 
default: 1k 
context: http, server 
Directive sets the headerbuffer size for the request header from client. 
For the overwhelming majority of requests it is completely sufficient a buffer size of 1K. 
However if a big cookie is in the request-header or the request has come from a wap-client the header can not be placed in 1K, therefore, the request-header or a line of request-header is not located completely in this buffer nginx allocate a bigger buffer, the size of the bigger buffer can be set with the instruction large_client_header_buffers. 


large_client_header_buffers 
syntax: large_client_header_buffers number size 
default: large_client_header_buffers 4 4k/8k 
context: http, server 
Directive assigns the maximum number and size of buffers for large headers to read from client request. 
The request line can not be bigger than the size of one buffer, if the client send a bigger header nginx returns error “Request URI too large” (414). 
The longest header line of request also must be not more than the size of one buffer, otherwise the client get the error “Bad request” (400). 
Buffers are separated only as needed. 
By default the size of one buffer is equal to the size of page, depending on platform this either 4K or 8K, if at the end of working request connection converts to state keep-alive, then these buffers are freed. 

对于apache2来说,它默认值是8k 
可以调整以下2个参数 
LimitRequestLine 16k 
LimitRequestFieldSize 16k 
LimitRequestLine 指令设置的是每一个header长度的上线

LimitRequestLine 指令 
说明 限制接受客户端发送的HTTP请求行的字节数 
语法 LimitRequestLine bytes 
默认值 LimitRequestLine 8190 
作用域 server config 
状态 核心(C) 
模块 core 
bytes将设置HTTP请求行的字节数限制。 
LimitRequestLine 指令允许服务器管理员增加或减少客户端HTTP请求行允许大小的限制。因为请求行包括HTTP方法、URI、协议版本,所以 LimitRequestLine指令会限制请求URI的长度。服务器会需要这个值足够大以装载它所有的资源名,包括可能在GET请求中所传递的查询部分的所有信息。 
这个指令给了服务器管理员更大的可控性以控制客户端不正常的请求行为。这有助于避免某些形式的拒绝服务攻击。 

LimitRequestFieldSize指令设置的是所有header总长度的上限值

LimitRequestFieldSize 指令 
说明 限制客户端发送的请求头的字节数 
语法 LimitRequestFieldsize bytes 
默认值 LimitRequestFieldsize 8190 
作用域 server config 
状态 核心(C) 
模块 core 
bytes指定了HTTP请求头允许的字节大小。 
LimitRequestFieldSize 指令允许服务器管理员增加或减少HTTP请求头域大小的限制。一般来说,服务器需要此值足够大,以适应普通客户端的任何请求的头域大小。一个普通头域的大小对于不同的客户端来说是有很大差别的,一般与用户配置他们的浏览器以支持更多的内容协议密切相关。SPNEGO的认证头最大可能达到12392字节。 
这个指令给了服务器管理员更大的可控性以控制客户端不正常的请求行为。这有助于避免某些形式的拒绝服务攻击。

Nginx和Apache的Rewrite规则实例对比


1.一般简单的Nginx和Apache规则的区别不大,基本能够完全兼容,例如:
Apache: RewriteRule  ^/abc/$   /web/abc.php [L]
Nginx:  rewrite  ^/abc/$  /web/abc.php last ;

我们可以看出来只要把Apache的RewriteRule改为Nginx的rewrite,Apache的[L]改为last 即可。

如果将Apache的规则改为Nginx规则后,用命令Nginx -t 检查发现错误,则我们可以尝试给条件加上引号,例如:

rewrite “^/([0-9]{5}).html$”   /x.php?id=$1 last;

2.Apache和Nginx的Rewrite规则在URL跳转时有细微区别:
Apache:  RewriteRule ^/html/([a-zA-Z]+)/.*$  /$1/  [R=301,L]
Nginx:   rewrite ^/html/([a-zA-Z]+)/.*$  http://$host/$1/ premanent ;

我们可以看到在Nginx的跳转中,我们需要加上http://$host,这是在Nginx中强烈要求的。

3.下面是一些Apache和Nginx规则的对应关系

a.Apache的RewriteCond对应Nginx的if

b.Apache的RewriteRule对应Nginx的rewrite

c.Apache的[R]对应Nginx的redirect

d.Apache的[P]对应Nginx的last

e.Apache的[R,L]对应Nginx的redirect

f.Apache的[P,L]对应Nginx的last

g.Apache的[PT,L]对应Nginx的last

例如:允许指定的域名访问本站,其他的域名一律转向www.freeoa.net

Apache:

RewriteCond %{HTTP_HOST} !^(.*?)\.aaa\.com$ [NC]
RewriteCond %{HTTP_HOST} !^localhost$
RewriteCond %{HTTP_HOST} !^192\.168\.0\.(.*?)$
RewriteRule ^/(.*)$ http://www.freeoa.net [R,L]

Nginx:

if( $host ~* ^(.*)\.aaa\.com$ ){
set $allowHost ‘1’;
}
if( $host ~* ^localhost ){
set $allowHost ‘1’;
}
if( $host ~* ^192\.168\.1\.(.*?)$ ){
set $allowHost ‘1’;
}
if( $allowHost !~ ‘1’ ){
rewrite ^/(.*)$ http://www.freeoa.net redirect ;
}


Nginx 的配置文件 (conf/nginx.conf) 整体上分为如下几个部分:

区域     职责
全局块     配置和 Nginx 运行相关的全局配置
events 块     配置和网络链接相关的配置
http 块     配置代理、缓存、日志记录、虚拟主机等配置
server 块     配置虚拟主机的相关参数,一个 http 快中可以有多个 server 块
location 块     配置请求的路由,以及各种页面的处理情况

比较全的配置文件示例如下

# 以下是全局段配置
#user nginx freeoa;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #设置进程数,默认为1
#pid /nginx/pid/nginx.pid; #指定nginx进程运行文件存放地址
error_log log/error.log debug;  #制定日志路径,级别:debug|info|notice|warn|error|crit|alert|emerg
# events段配置信息
events {
    accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on
    multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
    #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大连接数
}
# http、配置请求信息
http {
    include       mime.types;   #文件扩展名与文件类型映射表
    default_type  application/octet-stream; #默认文件类型,默认为text/plain
    #access_log off; #取消服务日志    
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
    access_log log/access.log myFormat;  #combined为日志格式的默认值
    sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
    sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
    keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。

    upstream mysvr {   
      server 127.0.0.1:4321;
      server 192.168.10.121:1234 backup;  #热备
    }
    error_page 404 https://www.noexist.com; #错误页
    # 第一个Server区块开始,表示一个独立的虚拟主机站点
    server {
        keepalive_requests 120; #单连接请求上限次数。
        listen       4545;   #监听端口
        server_name  127.0.0.1;   #监听地址       
        location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
           #root path;  #根目录
           #index vv.txt;  #设置默认页
           proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
           deny 127.0.0.1;  #拒绝的ip
           allow 172.18.1.2; #允许的ip           
        }
    }
}

路径映射

1、格式
location [ = | ~ | ~* | !~ | !~* | @ ] uri {...}

2、解释
= 表示精确匹配,如果找到,立即停止搜索并立即处理此请求。
~ 表示执行一个正则匹配,区分大小写匹配
~* 表示执行一个正则匹配,不区分大小写匹配
!~ 区分大小写不匹配
!~* 不区分大小写不匹配
^~ 即表示只匹配普通字符(空格)。使用前缀匹配,^ 表示 “非”,即不查询正则表达式。如果匹配成功,则不再匹配其他 location。
@ 指定一个命名的 location,一般只用于内部重定向请求。例如 error_page, try_files

uri 是待匹配的请求字符串,可以不包含正则表达式,也可以包含正则表达式;

3、优先级和示例
•[不加] < [~/~*] < [^~] < [=]
•示例如下:

location = / {
    # 精确匹配/,主机名后面不能带任何字符串 /
    # 只匹配http://abc.com
    # http://abc.com [匹配成功]
    # http://abc.com/index [匹配失败]
}
location ^~ /img/ {
      #以 /img/ 开头的请求,都会匹配上
    #http://abc.com/img/a.jpg   [成功]
    #http://abc.com/img/b.mp4  [成功]
}
location ~* /Example/ {
  # 则会忽略 uri 部分的大小写
  #http://abc.com/test/Example/ [匹配成功]
  #http://abc.com/example/ [匹配成功]
}
location /documents {
    # 如果有正则表达式可以匹配,则优先匹配正则表达式。
    #http://abc.com/documentsabc [匹配成功]
}
location / {
    #http://abc.com/abc [匹配成功]
}

反向代理 (Reverse Proxy) 是指以代理服务器来接受 internet 上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给 internet 上请求连接的客户端。真实的服务器不能直接被外部网络访问,所以需要一台代理服务器,而代理服务器能被外部网络访问的同时又跟真实服务器在同一个网络环境,当然也可能是同一台服务器,端口不同而已。其通过 proxy_pass 指令来实现,配置示例如下:

server {
    listen       80;
    server_name  localhost;

    location / {
         proxy_pass http://localhost:8081;
         proxy_set_header Host $host:$server_port;#为请求头添加Host字段,用于指定请求服务器的域名/IP地址和端口号。  

         # 设置用户ip地址
         proxy_set_header X-Forwarded-For $remote_addr;#为请求头添加XFF字段,值为客户端的IP地址。
         # 当请求服务器出错去寻找其他服务器
         proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
    
}

当访问 localhost 的时候,Nginx 就将请求转到 localhost:8081 了。

常用的指令

return 指令

返回 http 状态码和可选的第二个参数可以是重定向的 URL
return code [text];
return code URL;
return URL;

例如:
location / {
 return 404; # 直接返回状态码
}
location / {
 return 404 "pages not found"; # 返回状态码 + 一段文本
}
location / {
 return 302 /bbs ; # 返回状态码 + 重定向地址
}
location / {
 return https://www.baidu.com ; # 返回重定向地址
}

rewrite

重写 URI 请求 rewrite,通过使用 rewrite 指令在请求处理期间多次修改请求 URI,该指令具有一个可选参数和两个必需参数。
第一个 (必需) 参数是请求 URI 必须匹配的正则表达式。
第二个参数是用于替换匹配 URI 的 URI。

可选的第三个参数重写策略
• last 重写后的 URL 发起新请求,再次进入 server 段,重试 location 的中的匹配;
• break 直接使用重写后的 URL ,不再匹配其它 location 中语句;
• redirect 返回 302 临时重定向;
• permanent 返回 301 永久重定向;

location /users/ {
    rewrite ^/users/(.*)$ /show?user=$1 break;
}

error_page

使用 error_page 指令可以配置 NGINX 返回自定义页面以及错误代码,替换响应中的其他错误代码,或将浏览器重定向到其他 URI。在以下示例中,error_page 指令指定要返回 404 页面错误代码的页面 (/404.html)。

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

日志

访问日志:需要开启压缩 gzip on; 否则不生成日志文件,打开 log_format、access_log 注释
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  /usr/local/nginx/logs/host.access.log  main;

deny 、allow 指令

#禁止访问某个目录
location / {
    allow 192.168.0.0;
    allow 127.0.0.1;
    deny all;
#这段配置值允许192.168.0.0/24网段和127.0.0.1的请求,其他来源IP全部拒绝。
}

内置变量


nginx 的配置文件中可以使用的内置变量以美元符$开始,其中大部分预定义的变量的值由客户端发送携带。


Nginx访问控制

1、nginx 访问控制模块

(1)基于IP的访问控制:http_access_module
(2)基于用户的信任登录:http_auth_basic_module

2、基于IP的访问控制

1)、配置语法
Syntax:allow address | CIDR | unix: | all;
default:默认无
Context:http,server,location
 
Syntax:deny address | CIDR | unix: | all;
default:默认无
Context:http,server,location

2)、修改/etc/nginx/conf.d/access_mod.conf内容如下:
server {
    listen 80;
    server_name localhost;
    location ~ ^/admin {
        root /home/www/html;
        index index.html index.hml;
        deny 192.168.1.8;
        allow all;
        #deny 192.168.1.8;
        }
}

#需要注意:
如果先允许访问,再定义拒绝访问,那么拒绝访问不生效。

虚拟机宿主机IP为192.168.1.8,虚拟机IP为192.168.1.11,故这里禁止宿主机访问,允许其他所有IP访问。宿主机访问http://192.168.1.11/admin,显示403 Forbidden。当然也可以反向配置,同时也可以使用IP网段的配置方式,如allow 192.168.1.0/24;,表示满足此网段的IP都可以访问。

3)、指定location拒绝所有请求
如果你想拒绝某个指定URL地址的所有请求,而不是仅仅对其限速,只需要在location块中配置deny all指令:
server {
    listen 80;
    server_name localhost;
    location /foo.html {
        root /home/www/html;
        deny all;
        }
}

3、基于用户的信任登录

1)、配置语法
Syntax:auth_basic string | off;
default:auth_basic off;
Context:http,server,location,limit_except
 
Syntax:auth_basic_user_file file;
default:默认无
Context:http,server,location,limit_except
file:存储用户名密码信息的文件。

2)、配置示例
改名access_mod.conf为auth_mod.conf,内容如下:
server {
    listen 80;
    server_name localhost;
    location ~ ^/admin {
        root /home/www/html;
        index index.html index.hml;
        auth_basic "Auth access test";
        auth_basic_user_file /etc/nginx/auth_conf;
        }
}

auth_basic不为off,开启登录验证功能,auth_basic_user_file加载账号密码文件。

3)、建立口令文件
# mkdir /home/www/html/admin -p
# vim /home/www/html/admin
hello freeoa
# yum install -y httpd-tools #htpasswd是开源 http 服务器 apache httpd 的一个命令工具,用于生成 http 基本认证的密码文件
# htpasswd -cm /etc/nginx/auth_conf user10 //第一次新建用户
# htpasswd -m /etc/nginx/auth_conf user20 //第二次添加用户
# cat /etc/nginx/auth_conf

4)、访问测试

5)、局限性
(1)用户信息依赖文件方式
(2)操作管理机械,效率低下

NginxReverseProxy
1. Nginx & Apache 
2. Nginx Installation 
1). Nginx configuration for proxy behavior 
2). Nginx vhost proxy example 
3. Apache configuration 
1). Apache to use proxy 


Nginx & Apache
Working with virtual servers (like OpenVZ containers or XEN dom's) you might need a load balancing or a proxy solution to be able to run services from inside those machines through your host's single public IP address. Here you will find how to solve such a situation using Nginx and Apache. (Apache already has mod_proxy module which can be used instead of Nginx, but the second one is much lighter and scalable, so I recommend you using it.) 


Note: This tutorial assumes you already have a working environment like the one described above. 


Nginx Installation
Just use your favorite package manager and install nginx package: 
apt-get install nginx 

Nginx configuration for proxy behavior 
Nginx uses the following directives (as an example) in it's configuration files to behave like a proxy: 
proxy_redirect          off; 
proxy_set_header        Host            $host; 
proxy_set_header        X-Real-IP       $remote_addr; 
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for; 
client_max_body_size    10m; 
client_body_buffer_size 128k; 
proxy_connect_timeout   90; 
proxy_send_timeout      90; 
proxy_read_timeout      90; 
proxy_buffers           32 4k; 

Create the file /etc/nginx/proxy.conf containing all the informations above. We will include this file in every nginx vhost we need to be a proxy. 

Nginx vhost proxy example
Create an nginx vhost by creating a file inside /etc/nginx/sites-enabled/ like this:
server {
listen   80;
server_name  foo.bar.no foo.bar.yes foo.bar.ok;
access_log  /var/log/nginx/access.log;
location / {
 proxy_pass      http://172.27.0.2/;
 include         /etc/nginx/proxy.conf;
}
}
 
Or 
location / { 
            proxy_pass         http://127.0.0.1:8080/; 
            proxy_redirect     off; 
            proxy_set_header   Host             $host; 
            proxy_set_header   X-Real-IP        $remote_addr; 
            proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for; 
            client_max_body_size       10m; 
            client_body_buffer_size    128k; 
            proxy_connect_timeout      90; 
            proxy_send_timeout         90; 
            proxy_read_timeout         90; 
            proxy_buffer_size          4k; 
            proxy_buffers              4 32k; 
            proxy_busy_buffers_size    64k; 
            proxy_temp_file_write_size 64k; 


The example above will be a proxy for every domain listed with server_name, and the server which will be used for proxy is under proxy_pass directive. 

Done with nginx. Reload it: 
invoke-rc.d nginx reload 

Apache configuration
This assumes you are working on a machine behind the host that uses nginx as a proxy ( an OpenVZ container, XEN dom or a machine inside your network which is connected to the host we installed Nginx before) 

Apache to use proxy
Apache will doesn't know who connects to it except the host ip address we set up nginx. To repair this, we need to install Apache's mod_rpaf. Use your favorite package manager to install libapache2-mod-rpaf: 
apt-get install libapache2-mod-rpaf 

mod_rpaf requires the following directives inside a vhost to work: 
<IfModule mod_rpaf.c> 
 RPAFenable On 
 RPAFsethostname On 
 RPAFproxy_ips 172.27.0.1 
</IfModule> 

Where RPAFproxy_ips can be multiple IP addresses, one of which is our Nginx proxy private IP address. 

Compression
A great feature of nginx is its gzip compression capabilities, which make better use of upstream bandwidth completely transparently to the user. Enabling this is straightforward within in the http directive, 

# Enable compression 
 gzip on; 
 gzip_buffers 16 8k; 
 gzip_comp_level 9; 
 gzip_http_version 1.0; 
 gzip_min_length 0; 
 gzip_types text/plain text/css image/x-icon application/x-perl application/x-httpd-cgi application/x-javascrip; 
 gzip_vary on; 

The text content of web sites compresses well so users will experience a more responsive site. The maximum compression (level 9) is well worth implementing as the CPU overhead is minimal compared to the transmission time savings, at least at DSL speeds.


Security
Rewrite Rules 
Much of the security functionality is based on rewrite rules, which enable nginx to convert URLs on-the-fly. In this way the actual web server can be more shielded from misuse, and these rules can also be used to change the presentation of URLs. 

NginX rewrite rule syntax is somewhat awkward for those unfamiliar with this technology, but fortunately there are plenty of examples readily accessible with Google's help and some documentation in the NginX wiki itself at http://wiki.nginx.org/NginxHttpRewriteModule. 

Filtering 
Actions can also be defined in nginx based on specific pattern matching in the URLs requested. For example, requests for images can be filtered based on the HTTP referrer field (usually the URL of the page attempting to load the content) by comparing it to the host header being published, returning an error (HTTP 444) if they don't match to prevent image and content hijacking, which involves another website using images or content from yours, so that you are paying the bandwidth costs and providing free content. 

The code for this is added to the server definition, 
# Stop Image and Document Hijacking 
  location ~* (/.jpg|/.png|/.css)$ { 
  if ($http_referer !~ ^(http://www.example.com) ) { return 444; } 


Default Rules
When publishing multiple hosts with a single address using host-headers, it's vital to maintain the separation between services. Part of this separation is to consider explicitly what is returned when an attempt is made to connect by IP address alone, for example by a bot. Most likely the desired action will be to deny the request outright, in which case the following code can be used as the first server definition: 
 server { 
   listen 80; 
   server_name _; 
   return 444; 
}

nginx.conf example-nginx配置示例
Using the above and a few more of the capabilities described at https://calomel.org/nginx.html, a slightly more complicated conf file example is given below. There is a particularly good list of examples at http://wiki.opennet.ru/Nginx, albeit that some of the narrative is not in English. 
###########################################
### General Server Settings             ###
#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; 


########################################### 
### Reverse Proxy Listener Definitions  ### 

http { 
 # increase default size of 32 characters if there are long host names 
 server_names_hash_bucket_size 64; 
 # Prevent nginx version number being displayed on error pages 
 server_tokens off; 


 # Enable compression 
 gzip on; 
 gzip_buffers 16 8k; 
 gzip_comp_level 9; 
 gzip_http_version 1.0; 
 gzip_min_length 0; 
 gzip_types text/plain text/css image/x-icon application/x-perl application/x-httpd-cgi application/x-javascrip; 
 gzip_vary on; 

 # Size Limits & Buffer Overflows Mitigations 
 client_body_buffer_size  1K; 
 client_header_buffer_size 1k; 
 client_max_body_size 1k; 
 large_client_header_buffers 2 1k; 

 # Timeouts 
 client_body_timeout   10; 
 client_header_timeout 10; 
 keepalive_timeout     5 5; 
 send_timeout          10; 

 # Store session states in zone slimits - 32,000 sessions with 32 bytes/session/1m 
 limit_zone slimits $binary_remote_addr 5m; 

 # Restricts connections from a single ip address 
 limit_conn slimits 4; 
 server { 
   listen 80; 
   server_name host1.example.com; 
   # Only allow the most basic request methods 
   if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; } 
   # Block download agents 
   if ($http_user_agent ~* LWP::Simple|BBBike|wget|Baiduspider|Jullo) { return 403; } 
   # Block some robots 
   if ($http_user_agent ~* msnbot|scrapbot) { return 403; } 
   # Deny certain Referers 
   if ( $http_referer ~* (babes|forsale|girl|jewelry|love|nudit|organic|poker|porn|sex|teen) ) { return 403; } 

   location / {
     proxy_pass http://internal-server-host-1:80;
     proxy_set_header host host1.example.com;
   }
 }

 server {
   listen 80; 
   server_name host2.example.com; 
   # Block download agents 
   if ($http_user_agent ~* LWP::Simple|BBBike|wget|Baiduspider|Jullo) { return 403; } 
   # Block some robots 
   if ($http_user_agent ~* msnbot|scrapbot) { return 403; } 
   # Deny certain Referers 
   if ( $http_referer ~* (babes|forsale|girl|jewelry|love|nudit|organic|poker|porn|sex|teen) ) { return 403; } 
   # Stop Image and Document Hijacking 
   location ~* (/.jpg|/.png|/.css)$ { 
     if ($http_referer !~ ^(http://host2.example.com) ) { return 444; } 
   } 
   location / {
     proxy_pass http://internal-server-host-2:80; 
     proxy_set_header host host2.example.com; 
   }
 }
 server {
   listen       80  default_server;
   server_name  _;
   return       444;
 }
}

########################################### 
### End of file ### 
 
Application Specific Configuration
SSL
To use NginX to reverse proxy SSL sessions, NginX itself will need the certificates for the sites being proxied, including the private keys. The nginix SSL guide covers the configuration of NginX for SSL in some detail. 

Certificates from existing Windows servers can be exported for use by nginx - see Exporting Windows SSL Certificates. Self-signed certificates can also created using OpenSSL. 

With the certificates copied into a suitable folder (for example, nginx/conf/ssl), a server directive can then be built for the SSL listener. 

server {
   listen 443;
   server_name secure.example.com;
   ssl on;
   ssl_certificate ssl/secure-server.pem;
   ssl_certificate_key ssl/secure-server.key;
   ssl_session_timeout 5m;
   ssl_protocols SSLv3 TLSv1;
   ssl_ciphers HIGH:!ADH:!MD5;
   ssl_prefer_server_ciphers on;
   location / {
     proxy_pass https://secure-server:443;
     proxy_set_header host secure.example.com;
   } 
 } 

If more than secure site will be published via nginx on the same IP, TLS SNI (RFC4366) must be implemented in OpenSSL and nginx, and supported by the client in order for the correct certificate to be served. See Updating OpenSSL and Building Nginx with TLS SNI Support. 

Outlook Web Access
Using additional location directives, we can redirect certain content to different servers, but in this case potentially making use of a single server SSL certificate. For example, Outlook Web Access, which runs entirely from /owa, can be incorporated using, 

location /owa {
  proxy_pass https://owa-server:443;
  proxy_set_header Destination $http_destination;
}


Nginx经典入门

Nginx是一个开源的高性能Web服务器和反向代理服务器。它由Igor Sysoev于2004年首次发布,旨在解决C10K问题(即单个服务器同时处理10,000个客户端连接的挑战)。以下是Nginx的主要特点和用途:

(1)架构:
采用事件驱动的异步非阻塞架构
使用多进程模型,每个工作进程可以处理数千个连接

(2)功能:
Web服务器:处理HTTP、HTTPS和其他协议的请求
反向代理:将请求转发到其他服务器
负载均衡器:在多个后端服务器之间分配流量
内容缓存:缓存静态和动态内容以提高性能

(3)性能:
高并发处理能力
低内存占用 -高效的静态文件服务

(4)可扩展性:
模块化设计,支持第三方模块
灵活的配置系统

(5)安全性:
支持SSL/TLS加密
可配置访问控制和身份验证

(6)其他功能:
HTTP/2支持
WebSocket支持
邮件代理服务器功能

Nginx因其性能、稳定性和功能丰富而广受欢迎,被用于从小型网站到大型互联网公司的各种场景中。它常被用作Web服务器、反向代理、负载均衡器,以及在微服务架构中的重要组件。

2、Nginx的主要用途有哪些

Nginx作为一款高性能的HTTP服务器和反向代理服务器,具有多种用途,广泛应用于现代Web架构中。以下是Nginx的主要用途:

(1)Web服务器
Nginx可以作为一个高性能的Web服务器,主要用于提供静态内容和处理动态内容的请求。它擅长处理静态文件,如HTML、CSS、JavaScript、图片和视频等,性能非常高。

(2)反向代理服务器
Nginx常用作反向代理服务器,代理客户端请求到后端服务器,并将服务器的响应返回给客户端。这种设置有助于提高安全性、隐藏后端服务器的细节、分担负载并提高性能。

(3)负载均衡器
Nginx可以配置为负载均衡器,将客户端请求分发到多个后端服务器。它支持多种负载均衡算法,如轮询(Round Robin)、最少连接(Least Connections)、IP哈希(IP Hash)等,能够提高应用的可用性和性能。

(4)HTTP缓存
Nginx可以作为一个缓存服务器,缓存后端服务器的响应,从而减少对后端服务器的请求,提高响应速度和减少延迟。Nginx的缓存功能可以显著提升Web应用的性能,特别是在处理大量静态资源时。

(5)SSL/TLS转发
Nginx可以处理SSL/TLS,将HTTPS请求解密后再转发到后端服务器。这种方式可以减轻后端服务器的负担,并集中管理SSL证书。

(6)内容分发网络(CDN)
Nginx可以作为CDN的边缘服务器,缓存和分发静态内容。它能有效地减少服务器的负载,提高内容分发的速度和效率。

(7)API网关
在微服务架构中,Nginx可以作为API网关,处理来自客户端的API请求,并将这些请求转发到相应的后端服务。API网关还可以执行认证、授权、流量控制和监控等功能。

(8)动静分离
Nginx可以将动态请求和静态请求分离处理。例如,将静态资源(如图片、CSS、JS文件)直接由Nginx处理,而将动态请求(如PHP、Python等)转发到应用服务器处理。

(9)HTTP/2支持
Nginx支持HTTP/2协议,能够提高网页加载速度和资源加载效率,特别是在多资源加载时显著提高用户体验。

(10)安全防护
Nginx可以配置访问控制、IP黑名单和白名单、请求限速等功能,帮助抵御DDoS攻击、暴力破解等安全威胁。

(11)邮件代理
Nginx还支持作为IMAP、POP3和SMTP邮件代理服务器,用于邮件服务的负载均衡和反向代理。

(12)URL重写和重定向
Nginx提供强大的URL重写和重定向功能,可以根据规则重写请求URL或进行重定向,这对于SEO优化和网站迁移非常有用。

(13)日志管理
Nginx可以记录详细的访问日志和错误日志,支持自定义日志格式,便于运维人员进行监控和问题排查。

(14)微服务架构
在微服务架构中,Nginx可以用于服务发现、负载均衡、流量管理和跨域资源共享(CORS)。

(15)小结
Nginx因其高性能、灵活性和丰富的功能集,成为现代Web开发和运维中的重要组件。无论是作为Web服务器、反向代理、负载均衡器,还是作为API网关、缓存服务器等,Nginx都能出色地完成任务,提高Web应用的性能和可靠性。

3、Nginx和Apache的区别是什么

Nginx和Apache是两款广泛使用的Web服务器软件,它们在设计架构、性能表现、使用场景和功能特性等方面有显著的区别。

以下是详细的比较:

(1)设计架构
Nginx,采用时间驱动和异步非阻塞架构。Nginx使用少量或单个的工作进程,每个进程可以处理成千上万的并发连接。这种架构使得Nginx在处理高并发请求时具有极高的性能和资源消耗。
Apache,采用进程驱动和线程驱动的架构。Apache提供了多种多路复用模型(Prefork、Worker、Event),每个请求通常由一个独立的进程或线程处理,这在高并发的情况下可能导致较高的资源消耗。

(2)性能
Nginx,在高并发场景下,表现尤为出色,能够高效处理大量并发连接而不会消耗大量的系统资源,适合高流量的网站和应用;
Apache,在低并发场景下,表现尚可,处理高并发时,性能较差系统资源消耗较大。

(3)配置和扩展性
Nginx,通过纯文本方式配置,如果运行时修改了Nginx配置文件,可以通过重新加载nginx -s reload,这个命令会使Nginx重新读取配置文件,而不需要停止服务。
Apache,与Nginx不同,修改Apache配置文件,通常需要重启服务,Apache支持平滑重启apachectl graceful,这种方式让Apache主进程重新读取配置文件,并允许现有的连接继续处理完毕,而不会中断当前的服务。

(4)静态内容处理
Nginx,可以直接从文件系统读取并返回文件,性能极高;
Apache,在高并发场景下,效率不如Nginx

(5)动态内容处理
Nginx,通常通过FastCGI、uWSGI、SCGI或HTTP反向代理与外部服务(如PHP-FPM、Python WSGI应用)通信来处理动态内容。
Apache,可以直接通过内部模块(如mod_php、mod_python、mod_perl)处理动态内容,减少了中间通信的开销。

(6)反向代理和负载均衡
Nginx,内置强大的反向代理和负载均衡功能,支持多种负载均衡算法(轮询、最少连接、IP哈希)和健康检查功能;
Apache,通过模块(如mod_proxy、mod_proxy_balancer)提供反向代理和负载均衡功能,但配置相对复杂,性能和灵活性不如Nginx。

(7)SSL/TLS处理
Nginx,高效处理SSL/TLS连接,支持SSL会话缓存和会话票证,能够减少SSL握手的开销;
Apache,也支持SSL/TLS,但性能和配置的简便性不如Nginx。

(8)使用场景
Nginx,适合高并发、需要快速响应的场景,如反向代理、负载均衡、静态文件服务器、内容分发网络(CDN)等。
Apache,适合需要灵活配置、动态内容处理的场景,如Web应用开发环境、需要大量模块支持的应用等。

4、修改Nginx配置文件,需要重启Nginx吗,为什么

修改Nginx配置文件,一般不需要重启Nginx,通过重新加载nginx -s reload就可以操作,这个命令会使Nginx重新读取配置文件并加载。从工作原理分析,为什么?

Nginx使用主进程-工作进程的模式,重新加载时,主进程会读取新的配置文件,然后它会优雅的关闭旧的工作进程,并重启新的工作进程。

新的工作进程使用新的配置文件,而旧的工作进程处理完当前请求后会自动退出。

也可以通过平滑重启systemctl restart nginx的方式重启,这种方式会等待所有连接处理完毕后重启,确保现有连接不会被中断。

5、重启Nginx有几种方式,有哪些不同?

(1)重新加载
命令:nginx -s reload 或 systemctl reload nginx
特点:不会中断现有连接
适用情况:适用于大多数修改配置文件的情况,比如添加新站点、修改反向代理设置、更新负载均衡等

(2)平滑重启
命令:nginx -s reload 或 systemctl reload nginx
特点:不会中断现有连接,等现有连接执行完毕后再关闭
适用情况:修改大多数配置项,需要应用新配置但不想中断服务

(3)完全重启
命令:systemctl restart nginx 或 service nginx restart
特点:停止所有Nginx进程,然后重新启动,会中断所有当前请求连接
适用情况:
安装新的Nginx版本
添加或删除核心模块
修改需要完全重启才能生效的全局配置

(4)强制重启
命令:systemctl restart nginx 或 service nginx restart
特点:完全停止服务后重新启动,不会等待当前请求处理完成,重新加载所有配置和模块
适用情况:
Nginx进程出现异常,无法正常响应其他重启命令时;
系统资源出现问题,需要完全释放并重新分配。

6、热升级的命令、特点、适用场景都是什么

(1)命令
① 验证新的Nginx二进制文件:
/path/to/new/nginx -t

② 启动新的Nginx主进程:
/path/to/new/nginx -c /path/to/nginx.conf -g "daemon off;"

③ 向当前Nginx主进程发送 USR2 信号:
kill -USR2 `cat /path/to/nginx.pid`

④ 向旧的Nginx主进程发送 WINCH 信号:
kill -WINCH `cat /path/to/oldnginx.pid`

⑤ 在确认新版本运行正常后,向旧的Nginx主进程发送 QUIT 信号
kill -QUIT `cat /path/to/oldnginx.pid.oldbin`

(2)特点
不中断服务:热升级过程中,现有的Nginx进程会继续处理现有的连接,新进程会处理新的连接,从而保证服务的连续性。
零停机时间:与完全停止和启动不同,热升级不会中断现有连接,适用于需要高可用性的生产环境。
并行运行:旧的和新的Nginx主进程可以同时运行一段时间,允许平滑过渡和问题回滚。

(3)适用场景
升级Nginx版本:在需要升级Nginx版本但不希望中断服务的情况下,热升级是最优选择。
重大配置更改:当配置更改涉及到核心模块或对现有连接影响较大时,使用热升级可以确保现有连接的稳定性和新配置的应用。
高可用性要求:在金融、电子商务、在线游戏等对服务连续性要求极高的行业,热升级可以最大限度地减少服务中断风险。

7、平滑重启和热升级有什么不同?

(1)范围
平滑重启主要针对配置更改,不中断现有连接。
热升级用于软件版本的升级,不中断服务。

(2)复杂性
平滑重启操作简单,适合常规的配置更改
热升级更复杂,涉及多个步骤和手动干预

(3)回滚
平滑重启可以通过再次重载旧配置来回滚
热升级需要更复杂的回滚过程,可能需要重新安装旧版本

8、根据 “3.7SSL/TLS处理” 拓展:什么是SSL/TLS?有什么特点?有什么应用场景?

SSL(Secure Sockets Layer)和TLS(Transport Layer Security)是用于在网络上建立安全连接的加密协议。SSL是早期版本、TLS是SSL的升级版本。

(1)SSL/TLS特点
数据加密,SSL/TLS使用对称加密和非对称加密技术来确保数据在传输过程中的机密性,只有通信双方能够解密数据。
数据完整性,通过消息摘要算法(如SHA)确保数据在传输过程中没有被篡改,每个数据包都附带一个哈希值,接收方可以验证数据的完整性。
身份验证,使用数字证书和公钥基础设施(PKI)来验证通信双方的身份,确保数据被发送到指定的接收方。
防止重播攻击,SSL/TLS使用会话密钥和唯一会话ID来防止攻击者重发旧的通信数据。

(2)SSL/TLS的应用场景
HTTPS:最常见的应用场景,HTTPS用于保护Web浏览器和Web服务器之间的通信,确保用户数据在传输过程中不被窃取和篡改。
电子邮件:SSL/TLS用于保护电子邮件传输协议(如IMAP、POP3、SMTP),确保邮件客户端和邮件服务器之间的通信安全。
虚拟专用网络VPN:SSL/TLS用于VPN连接,确保远程访问和数据传输的安全性。
文件传输:保护文件传输协议(FTP、SFTP),确保文件在传输过程中的机密性和完整性。
即时通讯:保护即时通讯中的数据传输。
在线支付:确保在线支付平台和用户之间的交易数据安全。

(3)SSL/TLS 的详细流程
握手阶段
客户端问候;客户端发送支持的SSL/TLS版本、加密算法、压缩方法和随机数。
服务器问候:服务器选择SSL/TLS版本、加密算法、压缩方法,并发送服务器证书和随机数。
服务器密钥交换(可选):如果使用的加密算法需要,服务器会发送密钥交换信息。
客户端证书请求(可选):服务器请求客户端证书(双向认证时使用)。
服务器问候完成:服务器完成问候消息。
密钥交换和证书验证
客户端密钥交换:客户端生成一个预主密钥,并使用服务器的公钥加密后发送给服务器。
证书验证(可选):客户端发送其证书(双向认证时使用)。
客户端问候完成:客户端发送消息,表示其问候阶段已完成。
会话密钥生成:客户端和服务器根据交换的预主密钥和随机数生成对称会话密钥,用于加密后续数据。
数据传输:使用会话密钥加密和解密传输的数据。
关闭连接:结束SSL/TLS会话时,双方发送关闭通知,并终止连接。

(4)小结
SSL/TLS是现代互联网通信的基础,为Web浏览、电子邮件、文件传输、在线支付等提供了必要的安全保障。它们通过加密、身份验证和数据完整性保护确保了网络通信的机密性和安全性。

9、如何安装Nginx

安装Nginx的过程因操作系统不同而有所差异。

以下是针对不同操作系统的Nginx安装步骤:

(1)在Ubuntu/Debian上安装Nginx
更新包索引:apt update
安装Nginx:apt install nginx
启动Nginx:systemctl start nginx
设置Nginx开机自启:systemctl enable nginx
检查Nginx状态:systemctl status nginx

(2)在CentOS/RHEL上安装Nginx
安装EPEL仓库:yum install epel-release
安装Nginx:yum install nginx
启动Nginx:systemctl start nginx
设置Nginx开机自启:systemctl enable nginx
检查Nginx状态:systemctl status nginx

(3)在macOS上安装Nginx
安装Homebrew:/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
使用Homebrew安装Nginx:brew install nginx
启动Nginx:nginx
设置Nginx开机自启
检查Nginx状态:ps aux | grep nginx

(4)在Windows上安装Nginx
从Nginx官网下载适用于Windows的Nginx压缩包。
将下载的压缩包解压到一个文件夹中,例如 C:\nginx。
打开命令提示符,导航到Nginx解压目录下的 sbin 目录,然后运行:nginx.exe
设置Nginx开机自启:可以创建一个Windows服务来管理Nginx的启动和停止。可以使用 nssm(Non-Sucking Service Manager)来管理服务。

(5)检查Nginx是否安装成功
在浏览器中输入 http://localhost,如果看到Nginx的欢迎页面,说明Nginx已成功安装并运行。

10、Nginx有哪些基本命令?

启动Nginx:systemctl start nginx
停止Nginx:systemctl stop nginx
重新启动Nginx:systemctl restart nginx
重新加载Nginx配置:systemctl reload nginx
查看Nginx状态:systemctl status nginx

11、Nginx的配置文件路径是什么

Nginx的默认配置文件路径通常是:/etc/nginx/nginx.conf,这是主配置文件的位置。通常还有一些其他重要的配置目录和文件:
/etc/nginx/conf.d/ - 这个目录通常用于存放额外的配置文件;
/etc/nginx/sites-available/ 和 /etc/nginx/sites-enabled/ - 这两个目录用于管理虚拟主机配置;
/var/log/nginx/ - 日志文件通常存放在这里;
/usr/share/nginx/html/ - 默认的网站根目录。

需要注意的是,这些路径可能会根据你的具体安装和系统设置而有所不同。如果你需要确认你系统上的具体路径,可以使用以下命令:nginx -V,这会显示Nginx的编译选项,其中包括配置文件的路径。

12、详细介绍一下Nginx有哪些配置文件,它们的作用都是什么?

(1)/etc/nginx/nginx.conf
Nginx的主配置文件。它包含全局设置,如工作进程数、日志格式、默认的MIME类型等。通常,这个文件会包含一些 include 指令,用于引入其他配置文件。

(2)/etc/nginx/conf.d/
用于存放额外的配置文件。通常,主配置文件会包含一行 include /etc/nginx/conf.d/*.conf;,这样就会自动加载该目录下所有以 .conf 结尾的文件。这种方式使得配置更加模块化和易于管理。

(3)/etc/nginx/sites-available/ 和 /etc/nginx/sites-enabled/
sites-available 目录用于存储所有的虚拟主机配置文件。
sites-enabled 目录包含指向 sites-available 中实际要使用的配置文件的符号链接。这种设置允许您轻松地启用或禁用特定的网站配置,而无需删除配置文件。

(4)/var/log/nginx/
Nginx默认的日志目录。通常包含两种主要的日志文件:

access.log: 记录所有的HTTP请求
error.log: 记录Nginx运行时的错误和警告

(5)/usr/share/nginx/html/
Nginx默认的网站根目录,存放网站文件。但在实际使用中,通常会在虚拟主机配置中指定其他位置作为网站根目录。

(6)/etc/nginx/mime.types
这个文件定义了文件扩展名与MIME类型的映射关系,告诉Nginx如何正确地设置不同文件类型的Content-Type头。

(7)/etc/nginx/fastcgi_params 或 /etc/nginx/uwsgi_params
包含用于与FastCGI或uWSGI服务器通信的参数设置,通常用于PHP或Perl应用。

13、Nginx的默认端口是什么,如何更改Nginx的默认端口

Nginx 的默认端口是 80,用于处理 HTTP 请求。如果你启用了 HTTPS,则默认端口是 443。要更改 Nginx 的默认端口,需要修改其配置文件。

通常的步骤如下:

(1)打开 Nginx 配置文件
配置文件通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/default。你可以使用你喜欢的文本编辑器(如 vi、nano 等)打开它。
nano /etc/nginx/sites-available/default

(2)找到 server 块并修改端口
在配置文件中找到 server 块,修改 listen 指令来更改端口号。例如,要将端口更改为 8080,修改如下:
server {
listen 8080;
server_name your_domain_or_IP;

location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

(3)保存并关闭文件
保存文件并关闭编辑器。如果你使用的是 nano,按 Ctrl+X,然后按 Y 保存并按 Enter 退出。

(4)测试配置
测试 Nginx 配置文件以确保没有错误:
nginx -t

(5)重新加载 Nginx
如果配置文件没有错误,重新加载 Nginx 以应用更改:
systemctl reload nginx

这样Nginx就会在新的端口上监听了。可以通过浏览器访问 http://your_domain_or_IP:8080 来验证更改。

14、Nginx的主要配置指令有哪些

指令    用途    指令用法

核心配置指令
worker_processes    设置 Nginx 使用的工作进程数。    worker_processes auto;
error_log    指定错误日志文件及其日志级别。    error_log /var/log/nginx/error.log warn;
pid    设置存储 Nginx 主进程 ID 的文件路径。    pid /var/run/nginx.pid;

HTTP 配置指令
include    包含其他配置文件。    include /etc/nginx/conf.d/*.conf;
sendfile    启用高效的文件传输方式。    sendfile on;
keepalive_timeout    设置客户端连接保持活动的超时时间。    keepalive_timeout 65;

服务器配置指令
server    定义虚拟主机的配置信息。    server{listen 80;server_name example.com;}
server_name    设置服务器名称或域名。    server_name example.com www.example.com;
root    设置服务器的根目录。    root /var/www/html;
index    设置默认的主页文件。    index index.html index.htm;

位置配置指令
location    定义如何处理特定的 URL 请求。    
proxy_pass    配置反向代理的转发地址。    location / {proxy_pass http://localhost:3000;}
rewrite    用于 URL 重写。    location / {rewrite ^/oldpath/(.*)1 permanent;}

其他常见指令
access_log    指定访问日志文件及其格式。    access_log /var/log/nginx/access.log;
gzip    启用 gzip 压缩。    gzip on;
client_max_body_size    设置客户端请求主体的最大大小。    client_max_body_size 10m;

15、Nginx中的location指令有什么作用

在 Nginx 中,location 指令用于匹配 URI,并定义如何处理与这些 URI 相对应的请求。location 指令在服务器块 (server block) 中使用,它指定了 Nginx 应该如何处理某些路径的请求。通过使用不同的 location 配置,可以对不同的 URL 路径执行不同的操作,例如提供静态文件、反向代理、重定向等。

(1)location 指令的基本语法
location [modifier] [URI] {
# 指令
}

(2)location 指令的修饰符
Nginx 提供了几种不同的修饰符,用于控制 location 指令的匹配行为:

① 无修饰符:标准前缀匹配。如果多个 location 块匹配请求,Nginx 会选择最长的匹配。
location /images/ {
# 指令
}

② =:精确匹配。如果找到了精确匹配的 location 块,Nginx 将停止搜索并使用这个块。
location = /exact-match {
# 指令
}

③ ~:区分大小写的正则表达式匹配。
location ~ \.php$ {
# 指令
}

④ ~*:不区分大小写的正则表达式匹配。
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
# 指令
}

⑤ ^~:优先匹配。如果找到匹配的 location 块,Nginx 将停止搜索并使用这个块,而不会再检查正则表达式匹配。
location ^~ /static/ {
# 指令
}

(3)location 指令的示例

① 提供静态文件
提供位于服务器文件系统上的静态文件。
server {
listen 80;
server_name example.com;

location /images/ {
root /var/www/html;
}

location / {
root /var/www/html;
index index.html;
}
}

② 反向代理
将请求转发到后端服务器。
server {
listen 80;
server_name example.com;

location /api/ {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

③ 重定向请求
将请求重定向到另一个 URL。
server {
listen 80;
server_name example.com;

location /old-path {
return 301 /new-path;
}

location /new-path {
root /var/www/html;
index index.html;
}
}

④ 匹配特定文件类型
为特定文件类型配置缓存和访问日志。
server {
listen 80;
server_name example.com;

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
access_log off;
}
}

(4)匹配优先级
Nginx 按以下顺序匹配 location 块:
精确匹配 (=)。
前缀匹配 (^~)。
正则表达式匹配 (~ 或 ~*)。
标准前缀匹配。

以下是一个综合示例,展示了如何使用不同的 location 修饰符和匹配类型:
server {
listen 80;
server_name example.com;

# 精确匹配
location = / {
return 200 "This is the exact match for /";
}

# 优先前缀匹配
location ^~ /static/ {
root /var/www/static;
}

# 区分大小写的正则匹配
location ~ \.php$ {
proxy_pass http://php_backend;
}

# 不区分大小写的正则匹配
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
access_log off;
}

# 标准前缀匹配
location / {
root /var/www/html;
index index.html;
}
}

通过配置和使用 location 指令,Nginx 能够灵活地处理各种类型的请求,从而实现高效的请求管理和处理。

16、Nginx如何处理静态文件

Nginx 是一个高效的 HTTP 服务器,特别适合处理静态文件请求,如 HTML、CSS、JavaScript、图像和视频文件。以下是 Nginx 处理静态文件的主要配置步骤和相关指令:

(1)配置根目录
首先需要设置 Nginx 服务器的根目录,这个目录包含你的网站的静态文件。
server {
listen 80;
server_name example.com;

root /var/www/html;
index index.html index.htm;

location / {
try_files $uri $uri/ =404;
}
}

(2)配置 location 指令
location 指令用于定义如何处理特定路径的请求。在处理静态文件时,可以直接使用默认配置,Nginx 会在指定的 root 目录中查找文件。

location / {
try_files $uri $uri/ =404;
}

(3)启用 Gzip 压缩
为了提高传输效率,你可以启用 Gzip 压缩。这将减少传输的文件大小,从而加快加载时间。

http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}

(4)设置缓存控制头
配置缓存控制头可以帮助浏览器缓存静态文件,从而减少服务器负载并加快加载速度。

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}

(5)处理不同类型的静态文件
可以根据文件类型配置不同的处理方式。例如,对于图像文件、CSS 文件和 JavaScript 文件,设置不同的缓存时间或压缩策略。
location ~* \.(jpg|jpeg|png|gif|ico)$ {
expires 30d;
access_log off;
}

location ~* \.(css|js)$ {
expires 7d;
access_log off;
add_header Cache-Control "public";
}

(6)设置默认文档
可以通过 index 指令设置默认文档,例如 index.html。
location / {
index index.html;
}

(7)处理404错误
当请求的静态文件不存在时,可以配置一个自定义的404错误页面。

error_page 404 /404.html;
location = /404.html {
internal;
}

(8)完整示例配置
以下是一个完整的 Nginx 配置示例,用于处理静态文件:
server {
listen 80;
server_name example.com;

root /var/www/html;
index index.html index.htm;

location / {
try_files $uri $uri/ =404;
}

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
access_log off;
add_header Cache-Control "public";
}

location ~* \.(css|js)$ {
expires 7d;
access_log off;
add_header Cache-Control "public";
}

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

error_page 404 /404.html;
location = /404.html {
internal;
}
}

17、Nginx如何实现反向代理

Nginx 是一个强大的反向代理服务器,它可以将客户端请求转发到后台服务器,并将响应返回给客户端。以下是实现反向代理的主要步骤和相关配置指令:

(1)基本反向代理配置
最简单的反向代理配置是将所有请求转发到后端服务器。例如,将请求转发到在 localhost:3000 上运行的应用程序:
server {
listen 80;
server_name example.com;

location / {
proxy_pass http://localhost:3000;
}
}

(2)设置代理头
在反向代理配置中,通常需要设置一些头信息,以确保后端服务器能够正确处理请求。例如:
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

(3)处理 WebSocket
如果你的应用使用 WebSocket,需要在反向代理中添加额外的配置:
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

(4)配置负载均衡
Nginx 还可以用作负载均衡器,将请求分配到多个后端服务器。例如:
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}

server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

(5)设置代理超时
配置代理超时,以避免后端服务器响应过慢导致的问题:
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
send_timeout 60s;
}

(6)处理错误页面
配置自定义错误页面,以便在后端服务器不可用时提供友好的错误信息:
server {
listen 80;
server_name example.com;

location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

error_page 502 /502.html;
location = /502.html {
internal;
}
}

(7)完整示例配置
upstream backend {
server backend1.example.com;
server backend2.example.com;
}

server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
send_timeout 60s;
}

error_page 502 /502.html;
location = /502.html {
internal;
}
}

18、Nginx如何实现负载均衡

Nginx 是一个高效的负载均衡器,可以将客户端请求分配到多个后端服务器。以下是实现负载均衡的主要步骤和相关配置指令:

(1)定义后端服务器组
首先需要在 Nginx 配置中定义一组后端服务器。可以使用 upstream 指令来完成这一点。
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}

(2)配置负载均衡策略
Nginx 提供了几种不同的负载均衡策略:
轮询(默认):按顺序将请求分发到每个服务器。
权重:根据权重值分发请求。
IP哈希:根据客户端 IP 地址分发请求。
最少连接:将请求分发到当前活动连接数最少的服务器。

(3)配置反向代理
在服务器块中,使用 proxy_pass 指令将请求转发到定义的后端服务器组。
server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

(4)健康检查
Nginx 支持简单的被动健康检查,可以通过配置 proxy_next_upstream 指令来实现。如果某个服务器返回错误响应,Nginx 会将请求转发到下一个服务器。
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}

server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

(5)完整示例配置
upstream backend {
least_conn;
server backend1.example.com weight=3;
server backend2.example.com weight=2;
server backend3.example.com weight=1;
}

server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

通过这些配置,Nginx 可以有效地将客户端请求分发到多个后端服务器,从而实现负载均衡,提高应用的可用性和性能。

19、Nginx负载均衡有哪些算法

(1)轮询(默认)
这是 Nginx 的默认负载均衡策略,不需要额外配置。
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}

(2)权重
通过设置服务器的权重,可以控制请求分发的比例。
upstream backend {
server backend1.example.com weight=3;
server backend2.example.com weight=2;
server backend3.example.com weight=1;
}

(3)IP 哈希
使用 ip_hash 指令,根据客户端 IP 地址进行请求分发。
upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}

(4)最少连接
使用 least_conn 指令,将请求分发到当前活动连接数最少的服务器。
upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}

(5)URL 哈希
根据请求的 URL 进行请求分发。需要使用 hash 指令指定哈希的键。
upstream backend {
hash $request_uri;
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}

(6)随机
从两个随机选择的服务器中选择一个连接数较少的服务器来分发请求。这个算法可以有效地平衡负载。
upstream backend {
random two least_conn;
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}

通过这些配置,Nginx 可以根据不同的负载均衡算法将客户端请求高效地分发到多个后端服务器,提高应用的可用性和性能。

20、Nginx如何配置HTTPS

配置 Nginx 使用 HTTPS 涉及生成或获取 SSL/TLS 证书,并在 Nginx 配置文件中设置相关指令。以下是详细的步骤:

(1)获取 SSL/TLS 证书
可以通过以下几种方式获取 SSL/TLS 证书:
自签名证书:用于测试或内部使用。
从证书颁发机构(CA)获取:用于生产环境。可以使用 Let's Encrypt 免费获取证书。

(2)安装证书和密钥
将你的证书文件和私钥文件保存到服务器上的一个安全位置。假设证书文件为 example.com.crt,私钥文件为 example.com.key,它们存储在 /etc/nginx/ssl/ 目录中。

(3)配置 Nginx 使用 HTTPS
编辑 Nginx 配置文件(通常在 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/default),添加或修改 server 块以支持 HTTPS。以下是一个完整的示例配置:
server {
listen 80;
server_name example.com www.example.com;

# Redirect all HTTP requests to HTTPS
return 301 https://$host$request_uri;
}

server {
listen 443 ssl;
server_name example.com www.example.com;

# SSL certificate and key
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;

# SSL settings
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

# Additional security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload" always;
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options DENY;
add_header X-XSS-Protection "1; mode=block";

# Root and index files
root /var/www/html;
index index.html index.htm;

location / {
try_files $uri $uri/ =404;
}

# Proxy settings (if using as a reverse proxy)
# location / {
#     proxy_pass http://backend_server;
#     proxy_set_header Host $host;
#     proxy_set_header X-Real-IP $remote_addr;
#     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#     proxy_set_header X-Forwarded-Proto $scheme;
# }
}

(4)测试和重新加载 Nginx
配置完成后,测试 Nginx 配置文件以确保没有语法错误:
nginx -t

如果测试通过,重新加载 Nginx 以应用更改:
systemctl reload nginx

(5)自动续期
如果你使用 Let's Encrypt 获取证书,可以使用 Certbot 自动管理证书续期。安装 Certbot 并配置自动续期:
apt-get install certbot python3-certbot-nginx
certbot --nginx -d example.com -d www.example.com

Certbot 将自动编辑 Nginx 配置文件并设置证书续期任务。通过这些步骤,Nginx 将配置为使用 HTTPS 提供安全的 Web 服务。

21、如何在Nginx中设置虚拟主机

在 Nginx 中设置虚拟主机(也称为服务器块)允许你在同一台服务器上托管多个网站。

以下是详细的步骤:

(1)创建网站目录
首先,为每个网站创建一个独立的目录结构,例如:
mkdir -p /var/www/example.com/html
mkdir -p /var/www/test.com/html
chown -R $USER:$USER /var/www/example.com/html
chown -R $USER:$USER /var/www/test.com/html
chmod -R 755 /var/www

然后创建一个简单的 index.html 文件来测试每个站点:
echo "<html><head><title>Welcome to example.com!</title></head><body><h1>Success! The example.com server block is working!</h1></body></html>" | tee /var/www/example.com/html/index.html

echo "<html><head><title>Welcome to test.com!</title></head><body><h1>Success! The test.com server block is working!</h1></body></html>" | tee /var/www/test.com/html/index.html

(2)配置 Nginx 虚拟主机文件
在 /etc/nginx/sites-available/ 目录中为每个站点创建一个配置文件。
nano /etc/nginx/sites-available/example.com

添加以下内容:
server {
listen 80;
listen [::]:80;

server_name example.com www.example.com;

root /var/www/example.com/html;
index index.html;

location / {
try_files $uri $uri/ =404;
}
}

然后为另一个站点创建类似的配置:

nano /etc/nginx/sites-available/test.com

添加以下内容:

server {
listen 80;
listen [::]:80;

server_name test.com www.test.com;

root /var/www/test.com/html;
index index.html;

location / {
try_files $uri $uri/ =404;
}
}

(3)启用配置文件
通过在 /etc/nginx/sites-enabled/ 目录中创建符号链接来启用配置文件:
ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/test.com /etc/nginx/sites-enabled/

(4)测试配置并重新加载 Nginx
测试 Nginx 配置以确保没有语法错误:
nginx -t

如果测试通过,重新加载 Nginx 以应用更改:
systemctl reload nginx

(5)更新 DNS 记录
确保你的域名(如 example.com 和 test.com)的 DNS 记录指向你的服务器 IP 地址。

(6)访问网站
现在,你应该能够通过在浏览器中访问 http://example.com 和 http://test.com 来查看两个独立的网站。

(7)HTTPS 配置(可选)
如果你想为这些站点启用 HTTPS,可以使用 Let's Encrypt 获取免费的 SSL 证书。安装 Certbot 并运行以下命令:
apt-get install certbot python3-certbot-nginx
certbot --nginx -d example.com -d www.example.com
certbot --nginx -d test.com -d www.test.com

Certbot 将自动配置 Nginx 并设置证书续期任务。

通过这些步骤后就可以在 Nginx 中成功设置多个虚拟主机,每个主机可以托管不同的网站。

22、Nginx的工作模式有哪些

Nginx 的工作模式主要涉及其进程模型和请求处理方式。

(1)进程模型
Nginx 使用多进程模型来处理请求,主要包括以下几种进程:
Master 进程:负责管理 Worker 进程,处理配置文件的加载和热重启等任务。
Worker 进程:实际处理客户端请求,每个 Worker 进程都是独立的。

Master 进程的主要职责是:
读取和验证配置文件。
管理 Worker 进程的生命周期(启动、停止、重启)。
平滑地升级 Nginx 程序。

Worker 进程的职责是:
接受客户端连接。
处理和响应请求。

在 Nginx 配置文件中,可以通过 worker_processes 指令设置 Worker 进程的数量:
worker_processes auto;

auto 表示根据 CPU 的核心数自动设置。

(2)事件处理模型
Nginx 支持多种事件驱动模型,这使得它在处理高并发请求时具有很高的效率。Nginx 通过 worker_connections 指令设置每个 Worker 进程可以同时处理的最大连接数。其支持以下事件模型:
select:标准的事件通知机制,在所有平台上都可用,但性能较差。
poll:类似于 select,但性能更好。
epoll:Linux 2.6+ 内核中的高性能事件通知机制。
kqueue:用于 FreeBSD、OpenBSD 和 macOS 的高性能事件通知机制。
/dev/poll:用于 Solaris 的事件通知机制。
eventport:用于 Solaris 10 的事件通知机制。

Nginx 会自动选择最佳的事件模型,但也可以手动指定:
events {
use epoll;
worker_connections 1024;
}

(3)工作模式
Nginx 的工作模式主要是指它在处理请求时的角色和方式,包括:

① 反向代理模式
Nginx 作为反向代理服务器,接收客户端请求并将其转发给后端服务器,同时将后端服务器的响应返回给客户端。
server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

② 负载均衡模式
Nginx 可以分发客户端请求到多个后端服务器,实现负载均衡。
upstream backend {
server backend1.example.com;
server backend2.example.com;
}

server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

③ 静态文件服务模式
Nginx 可以直接从文件系统提供静态文件服务,如 HTML、CSS、JavaScript、图像等。
server {
listen 80;
server_name example.com;

root /var/www/html;
index index.html index.htm;

location / {
try_files $uri $uri/ =404;
}
}

④ Nginx 的模块化架构
Nginx 的模块化架构允许它在不同的工作模式下使用不同的模块,以提供灵活和高效的服务。例如:
HTTP 模块:处理 HTTP 请求和响应。
Stream 模块:处理 TCP/UDP 流量。
Mail 模块:处理电子邮件代理(SMTP/IMAP/POP3)。

通过配置和使用这些模块,Nginx 可以在各种工作模式下提供高效的服务。

(4)小结
Nginx 的工作模式主要通过其进程模型和事件驱动模型实现,并且可以在反向代理、负载均衡和静态文件服务等多种模式下高效工作。通过适当配置,Nginx 能够处理高并发请求并提供可靠的服务。

23、Nginx的事件驱动模型是什么

Nginx 的事件驱动模型是其高效处理并发连接和请求的核心机制之一。Nginx 通过事件驱动模型实现了非阻塞和异步 I/O 操作,使其能够在高并发环境中保持高性能和低资源消耗。

(1)事件驱动模型概述
在 Nginx 中,事件驱动模型是指通过事件通知机制处理大量并发连接和请求。这些机制能够在网络或文件 I/O 操作完成时通知 Nginx,从而避免阻塞等待。

(2)常见的事件驱动机制
Nginx 支持多种事件驱动机制,根据操作系统的不同选择最合适的机制:
select:一种标准的事件通知机制,支持所有平台,但性能较差。
poll:类似于 select,但性能更好,适用于大多数 UNIX 系统。
epoll:Linux 2.6+ 内核中的高性能事件通知机制,适用于大规模并发连接。
kqueue:用于 FreeBSD、OpenBSD 和 macOS 的高性能事件通知机制。
/dev/poll:用于 Solaris 的事件通知机制。
eventport:用于 Solaris 10 的事件通知机制。

(3)配置事件驱动模型
Nginx 会自动选择最佳的事件驱动机制,但也可以手动指定。
events {
use epoll;  # 使用 epoll 事件驱动机制
worker_connections 1024;  # 每个 worker 进程最大连接数
}

在这个示例中显式指定了 epoll 作为事件驱动机制,并设置每个 worker 进程最多处理 1024 个并发连接。

(4)事件驱动模型的工作原理
事件循环:每个 worker 进程都有一个事件循环,持续监听网络事件(如新连接、数据可读或可写等)。
事件注册:当一个新的网络连接到达时,Nginx 会将该连接的文件描述符(FD)注册到事件驱动机制中,并指定监听的事件类型(如可读、可写)。
事件通知:当事件发生时(如数据到达或连接关闭),事件驱动机制会通知 Nginx,Nginx 将事件放入事件队列中。
事件处理:Nginx 的事件循环从事件队列中取出事件,并调用相应的处理函数进行处理。

(5)高效的非阻塞 I/O
Nginx 的事件驱动模型通过非阻塞 I/O 和异步事件通知机制,实现了高效的请求处理:
非阻塞 I/O:Nginx 在处理 I/O 操作时不会阻塞,而是立即返回,允许其他操作继续进行。当 I/O 操作完成时,通过事件通知机制通知 Nginx。
异步事件通知:事件驱动机制会在事件发生时通知 Nginx,而不是让 Nginx 轮询检查,这样可以节省 CPU 资源,提高性能。

(6)负载均衡和反向代理中的事件驱动
在负载均衡和反向代理场景中,Nginx 的事件驱动模型尤为重要,因为它需要处理大量的并发连接。通过使用高效的事件驱动机制,Nginx 能够在高负载下保持低延迟和高吞吐量。

(7)小结
Nginx 的事件驱动模型是其高性能的关键,通过支持多种事件通知机制(如 epoll、kqueue 等),实现了非阻塞和异步 I/O 操作,使其能够高效处理大量并发连接和请求。这种设计使 Nginx 成为一个强大而灵活的 HTTP 服务器和反向代理服务器,适用于各种高并发场景。

24、如何优化Nginx的性能

优化 Nginx 的性能可以从以下几个方面入手,包括调整配置、优化系统参数、使用缓存和负载均衡等。

(1)调整 Nginx 配置
① 增加 Worker 进程数
将 worker_processes 设置为自动或根据 CPU 核心数设置适当的值,以充分利用多核 CPU 的性能。
worker_processes auto;

② 调整 Worker 连接数
增加 worker_connections 的值,以允许每个 Worker 进程处理更多的并发连接。
events {
worker_connections 4096;
}

③ 优化缓冲区和队列大小
调整缓冲区大小和队列参数,以处理大量请求数据。
http {
client_body_buffer_size 16K;
client_max_body_size 8M;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
}

(2)启用 Gzip 压缩
启用 Gzip 压缩可以减少传输的数据量,提高页面加载速度。
http {
gzip on;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 256;
}

(3)使用缓存
① 启用静态文件缓存
配置浏览器缓存头,以减少服务器负载并提高页面加载速度。

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}

② 启用代理缓存
如果 Nginx 作为反向代理,可以启用代理缓存。

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
location / {
proxy_cache my_cache;
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

(4)优化系统参数
① 调整文件描述符限制
增加文件描述符的限制,以允许更多的并发连接:
ulimit -n 65535

在 /etc/security/limits.conf 文件中添加:
* soft nofile 65535
* hard nofile 65535

② 调整 TCP 参数
调整系统的 TCP 参数,以提高网络性能。在 /etc/sysctl.conf 文件中添加:
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15

应用更改:
sysctl -p

(5)启用 HTTP/2
HTTP/2 提供了更好的性能和效率,特别是在处理多资源请求时:
server {
listen 443 ssl http2;
server_name example.com;

ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;

# 其他配置...
}

(6)使用负载均衡
将流量分配到多台后端服务器,以提高整体系统的处理能力和可靠性:
upstream backend {
server backend1.example.com;
server backend2.example.com;
}

server {
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

(7)监控和调优
持续监控 Nginx 的性能指标(如 CPU 使用率、内存使用率、响应时间等),并根据监控数据进行调整和优化。

可以使用工具如:
Grafana 和 Prometheus 进行性能监控和告警。
ngxtop 监控实时请求信息。
New Relic、Datadog 等进行综合性能监控。

通过上述配置和调整,可以显著提升 Nginx 的性能,使其在高并发环境下表现更加优异。

25、Nginx如何处理大并发请求

Nginx 处理大并发请求的能力主要依赖于其事件驱动模型、优化配置和系统资源的高效利用。以下是一些具体方法和配置,以帮助 Nginx 更好地处理大并发请求:

(1)使用事件驱动模型
Nginx 使用事件驱动模型(如 epoll、kqueue 等)来处理并发请求。这个模型允许 Nginx 在单个进程中高效地管理大量连接。

在 Nginx 配置文件中,确保选择适当的事件模型:
events {
use epoll;  # Linux 环境推荐使用 epoll
worker_connections 1024;  # 每个 worker 进程允许的最大连接数
}

(2)增加 Worker 进程数
根据服务器的 CPU 核心数设置 worker_processes 的值,以充分利用多核 CPU 的性能:
worker_processes auto;

(3)调整系统参数
① 调整文件描述符限制
增加文件描述符的限制,以允许更多的并发连接:
ulimit -n 65535

在 /etc/security/limits.conf 文件中添加:
* soft nofile 65535
* hard nofile 65535

② 调整 TCP 参数
在 /etc/sysctl.conf 文件中添加以下参数,以优化 TCP 性能:
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15

应用更改:
sysctl -p

(4)启用 Gzip 压缩
启用 Gzip 压缩以减少传输数据量,提高请求处理速度:
http {
gzip on;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 256;
}

(5)使用缓存
① 启用静态文件缓存
配置浏览器缓存头,以减少服务器负载并提高页面加载速度:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}

② 启用代理缓存
如果 Nginx 作为反向代理,可以启用代理缓存:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;

server {
location / {
proxy_cache my_cache;
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

(6)负载均衡
将流量分配到多台后端服务器,以提高整体系统的处理能力和可靠性:
upstream backend {
server backend1.example.com;
server backend2.example.com;
}

server {
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

(7)使用 HTTP/2
HTTP/2 提供了更好的性能和效率,特别是在处理多资源请求时:
server {
listen 443 ssl http2;
server_name example.com;

ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;

# 其他配置...
}

(8)调整超时设置
优化超时设置可以防止长时间挂起的连接占用资源:
http {
keepalive_timeout 65;
client_header_timeout 15;
client_body_timeout 15;
send_timeout 15;
}

(9)监控和调优
持续监控 Nginx 的性能指标(如 CPU 使用率、内存使用率、响应时间等),并根据监控数据进行调整和优化。

使用工具如:
Grafana 和 Prometheus 进行性能监控和告警。
ngxtop 监控实时请求信息。
New Relic、Datadog 等进行综合性能监控。

通过上述配置和调整,Nginx 能够高效处理大并发请求,确保在高负载下依然保持良好的性能和响应速度。