# Nginx 无感知 URL 跳转配置
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/03.%20%E8%BF%90%E7%BB%B4%E6%89%8B%E5%86%8C/01.%20%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/15.%20Nginx%E9%9A%90%E8%97%8F%E5%BC%8F%E8%B7%B3%E8%BD%AC


# Nginx 无感知 URL 跳转配置

Nginx 能够实现无感知 URL 跳转，即用户请求一个 URL，却被跳转到另一个页面，而浏览器地址栏中的 URL 保持不变。这种跳转通过 Nginx 的 `rewrite` 规则实现。以下是两个配置示例，展示如何实现这种跳转。

## 配置示例 1：HTTPS 跳转

将请求路径 `https://kevin.com/data/test` 跳转到 `https://rubao.com/data/test/test.html` 页面，同时保持 URL 不变。

```nginx
server {
    listen       443;
    server_name  kevin.com;
    access_log  /data/nginx/logs/kevin.com-access.log main;
    error_log  /data/nginx/logs/kevin.com-error.log;

    ssl on;
    ssl_certificate /data/nginx/ssl/kevin.com.crt;
    ssl_certificate_key /data/nginx/ssl/kevin.com.key;
    ssl_session_timeout 5m;

    location = /data/test {
        rewrite ^/data/test(.*)$ /data/test/test.html break;
        proxy_pass https://rubao.com;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
```

## 配置示例 2：内网请求跳转

将访问 `172.16.60.16:8082/m2/order/secretRecording` 的请求跳转到 `172.16.60.28:8089/order/secretRecording`，同时保持 URL 不变。

```nginx
server {
    listen 8082;
    server_name 172.16.60.16;
    index index.html index.php index.htm;

    location ~* ^/m2/order/secretRecording {
        proxy_next_upstream error timeout http_503 http_504 http_502;
        proxy_connect_timeout 500s;
        proxy_read_timeout 500s;
        proxy_send_timeout 500s;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        rewrite ^(.*)$ /order/secretRecording break;  # 改写URI地址
        proxy_pass http://172.16.60.28:8089;  # 跳转
    }
}
```

## 注意事项

1. 在使用 `proxy_pass` 时，确保正确设置了 `proxy_set_header`，以保持原始请求的头部信息。
2. 使用 `rewrite` 规则时，`break` 表示停止处理当前 location 的剩余规则，并开始执行新的 URI。
3. 确保 SSL 证书和密钥路径正确，以及 SSL 配置符合安全要求。
4. 调整超时设置以适应后端服务的响应时间。

通过这些配置，可以实现 Nginx 的无感知 URL 跳转，这对于某些需要隐藏实际服务地址或进行流量转发的场景非常有用。
