Nginx的几种代理方式
Nginx作为一个高性能的Web服务器,常用于反向代理、负载均衡和HTTP缓存。以下是几种常见的代理方式及其详细解释。
1. 反向代理 (Reverse Proxy)
反向代理服务器接受客户端的请求,将请求转发给后端服务器,并将后端服务器的响应返回给客户端。反向代理常用于负载均衡、缓存、SSL加速等场景。
配置示例
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;
}
}
参数说明
proxy_pass
: 指定后端服务器的地址,可以是IP地址或域名。proxy_set_header Host $host
: 设置Host头,以便后端服务器知道客户端访问的主机名。proxy_set_header X-Real-IP $remote_addr
: 将客户端的真实IP地址发送给后端服务器。proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for
: 传递客户端IP地址链,以便后端服务器知道请求的来源。proxy_set_header X-Forwarded-Proto $scheme
: 传递客户端使用的协议(http或https)。
2. 负载均衡 (Load Balancing)
Nginx可以将请求分发到多个后端服务器,以实现负载均衡。常见的负载均衡算法包括轮询、最少连接和IP哈希等。
配置示例
http {
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
}
参数说明
upstream
: 定义一个服务器池,包含多个后端服务器。server
: 指定后端服务器的地址,可以是IP地址或域名。proxy_pass http://backend
: 将请求转发到上面定义的服务器池。
负载均衡算法
- 轮询(默认):请求依次分发到不同的服务器。
least_conn
: 分发请求到连接数最少的服务器。upstream backend { least_conn; server backend1.example.com; server backend2.example.com; }
ip_hash
: 基于客户端IP地址分发请求,相同IP地址的请求会被分发到同一个服务器。upstream backend { ip_hash; server backend1.example.com; server backend2.example.com; }
3. HTTP缓存 (HTTP Caching)
Nginx可以缓存后端服务器的响应,以减少后端服务器的负载,提高响应速度。
配置示例
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
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;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
}
参数说明
proxy_cache_path
: 定义缓存存储路径及相关参数。/data/nginx/cache
: 缓存存储路径。levels=1:2
: 缓存文件的层次结构。keys_zone=my_cache:10m
: 定义一个共享内存区域,用于存储缓存键和元数据,大小为10MB。max_size=1g
: 缓存的最大存储空间为1GB。inactive=60m
: 在60分钟内没有被访问的缓存条目将被删除。use_temp_path=off
: 禁用临时路径。
proxy_cache my_cache
: 使用定义的缓存区域my_cache
。proxy_cache_valid
: 设置缓存的有效时间,根据响应状态码设置不同的缓存时间。
4. 快速CGI代理 (FastCGI Proxy)
Nginx可以通过FastCGI协议将请求转发给后端的应用服务器,如PHP-FPM。
配置示例
server {
listen 80;
server_name example.com;
location ~ \.php$ {
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
参数说明
location ~ \.php$
: 匹配以.php
结尾的请求。root
: 设置网站的根目录。fastcgi_pass
: 指定FastCGI服务器的地址和端口。fastcgi_index
: 设置FastCGI索引文件。fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name
: 设置FastCGI的参数,用于指定脚本文件的路径。include fastcgi_params
: 包含FastCGI相关的默认参数配置文件。
本文由mdnice多平台发布
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。