Nginx 配置转发规则
要素:
指令: server,location,rewrite
参数:
- listen: 监听端口
- server_name: 虚拟主机名
- location: 匹配的 URL 路径
- rewrite: 重写规则
- proxy_pass: 转发目标
用法:
nginx
server {
listen 80;
server_name example.com;
location / {
rewrite ^/(.)$ /$1 permanent;
proxy_pass http://backend-server:8080/;
}
}
解释:
- Nginx 监听端口 80,使用虚拟主机名 example.com。
- 对于所有匹配根路径 (/) 的请求,Nginx 将 URL 中的斜杠 (/) 重写为一个空格,并设置永久重定向。
- 然后,Nginx 使用 proxy_pass 将请求转发到后端服务器 http://backend-server:8080/。
其他示例:
转发特定 URL 路径:
nginx
location /api/ {
proxy_pass http://api-server:8081/;
}
基于请求头转发:
nginx
location / {
if ($http_user_agent ~ "iPhone" ) {
proxy_pass http://mobile-server:8082/;
} else {
proxy_pass http://desktop-server:8083/;
}
}