Nginx可以通过多种方式根据URL路径转发请求,以下是几种常见的配置方法:
server {
listen 80;
server_name example.com;
# 转发 /api/ 开头的请求到后端服务
location /api/ {
proxy_pass http://backend-server:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 转发其他请求到前端服务
location / {
proxy_pass http://frontend-server:3000;
}
}
使用 = 进行精确匹配:
location = /login {
proxy_pass http://auth-service/login;
}
使用 ~ (区分大小写) 或 ~* (不区分大小写) 进行正则匹配:
# 匹配图片请求
location ~* \.(jpg|jpeg|png|gif)$ {
root /var/www/images;
}
# 匹配特定模式的URL
location ~ ^/users/([0-9]+)/profile$ {
proxy_pass http://user-service/$1;
}
使用 rewrite 指令修改路径:
location /old-path/ {
rewrite ^/old-path/(.*) /new-path/$1 break;
proxy_pass http://new-service;
}
location /search {
if ($arg_query ~* "special") {
proxy_pass http://special-search-service;
}
proxy_pass http://regular-search-service;
}
location / {
# 检查多个条件
if ($uri ~ ^/api/v1/) {
proxy_pass http://api-v1;
}
if ($uri ~ ^/api/v2/) {
proxy_pass http://api-v2;
}
# 默认转发
proxy_pass http://default-service;
}
=)优先于前缀匹配,正则匹配性能最低Host 和 X-Real-IPupstream 模块结合使用实现负载均衡upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
需要更具体的配置示例或针对特定场景的解决方案,请提供更多细节。