Nginx配置问题:指定路径免重定向并保留URL不变
Nginx 域名重定向配置修正方案
需求回顾
- 把
landing.immancrze.us的所有请求重定向到app.immancrze.us - 唯独
landing.immancrze.us/potential-ownership要保持浏览器URL不变,直接返回内容(当前配置下该请求会跳转到app.immancrze.us/potential-ownership,不符合需求)
现有配置问题分析
- 路径匹配不全:原配置里的
location = /potential-ownership只匹配精确路径,一旦请求带尾斜杠(/potential-ownership/)或者子路径,就会触发最后的重定向规则; - 静态文件服务逻辑可能偏差:如果静态文件放在
/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
相关产品推荐
相关产品推荐

