- break:重写完成后不再继续匹配
- redirect:返回 302 重定向(临时重定向),客户端对重定向的 URL 发起新的请求
- permanent:返回 301 重定向(永久重定向),客户端对重定向的 URL 发起新的请求
一个 server 配置示例:
server {
listen 80;
server_name www.example.com;
root /web/htdocs;
location / {
index index.html index.htm;
}
location /status {
stub_status on;
allow 10.0.0.0/8;
deny all;
access_log off;
}
2.3 SSL 的配置
启用一个 SSL 虚拟主机
server {
listen 443;
server_name example.com;
root /apps/www;
index index.html index.htm;
ssl on;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
# ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
# ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
# ssl_prefer_server_ciphers on;
}
其中 ssl_certificate 表示 CA 文件,ssl_certificate_key 表示密钥文件。
如果想把 http 请求强制转到 https,可以这样:
server {
listen 80;
server_name example.me;
return 301 https://$server_name$request_uri;
}
2.4 nginx 做负载均衡反向代理
nginx 做反向代理时,后端主机有多台,可以使用 upstream 定义一个后端主机池,在反向代理时直接使用主机池的名字。在 upstream 中可以定义负载均衡调度算法,权重,健康状态检测等参数。
例如:
upstream backend {
server 172.16.0.1:80 weight=1 max-fails=3 fail_timeout=10;
server 172.16.0.2:80 weight=1max-fails=3 fail_timeout=10;;
}
默认请求下,使用 round-robin 调度算法,并有健康状态检查和恢复主机的能力。
ningx 还可以使用这些算法:
ip_hash:基于源地址哈希,主要目的是会话保持
least_conn:基于最少活动连接进行调度
sticky:基于 cookie 进行会话绑定,nginx 会在客户端第一次访问时插入路由信息到 cookie 中,或者选择 cookie 中的某个字段的值作为键,以后每次请求将基于此信息进行调度
基于 cookie 的会话绑定共有 cookie,route 和 learn 三种。
例如,基于 cookie name 的调度:
upstream backend {
server backend1.example.com;
server backend2.example.com;
sticky cookie srv_id expires=1h domain=.example.com path=/;
}
使用此主机组进行反向代理:
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_haeder X-Forwared-For $proxy_add_x_forwarded_for;
}
proxy_pass URL 指定代理的后端主机,可以指定 "http" 或 "https" 协议,域名可以是 ip 地址,也可以是 upstream 池名字
如果代理指定的是一个 URI 地址,如 http://127.0.0.1/remote,那么将直接被代理至指定 URI,无论请求的 URI 是什么








