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

Nginx出现rewrite或内部重定向循环问题求解决(附配置)

Nginx重定向循环问题解决方案

问题描述

查看GCP错误日志时出现重定向循环错误:

146039 rewrite or internal redirection cycle while internally redirecting to "/static/js/main.64520b4a.js"

对应的Nginx配置如下:

server {  
  listen 80 default_server;   
  listen [::]:80 default_server;  
  root /var/www/html;  
  server_tokens off;  
  
  location / {  
    if (-f $document_root/$maintenance_mode) {  
      rewrite ^(.*)$ /maintenance_page.html break;  
    }  
    try_files $uri /index.html =404;  
    proxy_set_header Host $host;  
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
    proxy_set_header X-Request-URI $request_uri;  
  }  
  
  location ~ .(static)/(js|css|media)/(.+)$ { 
    try_files $uri $uri/ /$1/$2/$3;  
  }  
}

问题原因

  1. 正则匹配错误:location ~ .(static)/(js|css|media)/(.+)$中的.是正则通配符(匹配任意单个字符),而非字面意义的分隔符,会错误匹配非目标路径;同时缺少起始锚点^/,可能触发非预期的路径匹配。
  2. try_files触发循环:try_files $uri $uri/ /$1/$2/$3中,当$uri对应的文件不存在时,最后一个参数会内部重定向到原请求路径,导致Nginx反复处理同一请求,形成循环。
  3. 冗余配置:location /中的proxy_set_header指令无意义,该location未配置proxy_pass,这些指令不会生效。

解决方案

修改后的配置

server {  
  listen 80 default_server;   
  listen [::]:80 default_server;  
  root /var/www/html;  
  server_tokens off;  
  
  location / {  
    if (-f $document_root/$maintenance_mode) {  
      rewrite ^(.*)$ /maintenance_page.html break;  
    }  
    try_files $uri /index.html =404;  
  }  
  
  # 修正正则,仅匹配/static开头的静态资源路径
  location ~ ^/static/(js|css|media)/ { 
    # 文件不存在时直接返回404,SPA场景可改为try_files $uri /index.html
    try_files $uri =404;  
  }  
}

关键调整说明

  • 修正静态资源路由匹配:用^/static/(js|css|media)/精准匹配目标静态资源路径,避免错误触发。
  • 简化try_files逻辑:静态资源不存在时直接返回404;若为单页应用,可改为try_files $uri /index.html,但需确保静态资源路径与前端路由无冲突。
  • 移除冗余指令:删掉location /中无用的proxy_set_header配置,精简配置文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:06:32