You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx配置问题:指定路径免重定向并保留URL不变

Nginx 域名重定向配置修正方案

需求回顾

  • 把 landing.immancrze.us 的所有请求重定向到 app.immancrze.us
  • 唯独 landing.immancrze.us/potential-ownership 要保持浏览器URL不变,直接返回内容(当前配置下该请求会跳转到 app.immancrze.us/potential-ownership,不符合需求)

现有配置问题分析

  1. 路径匹配不全:原配置里的 location = /potential-ownership 只匹配精确路径,一旦请求带尾斜杠(/potential-ownership/)或者子路径,就会触发最后的重定向规则;
  2. 静态文件服务逻辑可能偏差:如果静态文件放在 /usr/share/nginx/html/potential-ownership 目录下,原配置的 try_files 规则可能无法正确找到文件,间接触发重定向。

修正后的配置

server {
    listen 80;
    server_name landing.immancrze.us;

    # 匹配 /potential-ownership 及所有子路径,保持URL不变返回内容
    location ~ ^/potential-ownership(/.*)?$ {
        root /usr/share/nginx/html;
        index index.html;
        try_files $uri $uri/ /potential-ownership/index.html;
    }

    # 为该路径下的JS文件设置缓存控制头
    location ~ ^/potential-ownership/.*\.js$ {
        sendfile off;
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }

    # 其余所有请求统一重定向到app域名
    location / {
        return 301 http://app.immancrze.us$request_uri;
    }
}

关键调整说明

  • 宽范围路径匹配:用正则 ^/potential-ownership(/.*)?$ 覆盖精确路径、带尾斜杠的路径以及所有子路径,确保这类请求不会被重定向规则捕获;
  • 静态文件定位优化:try_files 最后指定 /potential-ownership/index.html,保证即使请求的子路径不存在,也能返回该页面的主文件;如果静态文件直接放在 /usr/share/nginx/html 根目录下,可把 root 换成 alias /usr/share/nginx/html;,并将 try_files 改为 $uri $uri/ /index.html;;
  • JS规则范围限定:把JS缓存规则限定在 /potential-ownership 路径下,避免影响其他重定向请求;
  • 简化根路径处理:移除单独的根路径重定向块,最后的 location / 会自动处理根路径请求,配置更简洁。

内容的提问来源于stack exchange,提问作者Himanshu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:40:14