【问题标题】:Nginx location / overrides all other locationsNginx 位置/覆盖所有其他位置
【发布时间】:2025-12-24 00:45:10
【问题描述】:

我正在尝试编写一个简单的 nginx 配置。我需要的是:

  1. 如果根目录中存在文件,则提供此文件
  2. 如果 url 是 /default/url 则显示 /some/path2/index.html
  3. 否则重定向到/default/url

我的配置如下

    server {
    listen 127.0.0.1:80;
    server_name my.domain.com;

    root /some/path/html;

    location / {
            return 302 /default/url; 
    }

    location = /default/url {
            rewrite ^/(.*)$/some/path2/index.html;
    }

    location /default/e_schema {
            proxy_pass http://other.host.com;
            proxy_http_version 1.1;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
    }
}

无论网址如何,它都会立即重定向到 /default/url。 我试图将 location / 块放在底部和顶部。我尝试使用 location ~ /.* 来降低优先级,但没有任何帮助。如果我完全删除 location / 一切都很好,我的要求 2 和 3 都可以。

根据这个答案https://serverfault.com/questions/656628/nginx-catch-all-other-locations-than-given/656634 它应该可以工作。

【问题讨论】:

    标签: nginx nginx-location


    【解决方案1】:

    您在位置块中放置了一个“=”

    location = /default/url {
    

    您可以尝试删除它吗?我相信它可能正在设置网址

    【讨论】:

    • 不,删除后=结果是一样的。我添加它是因为我需要完全匹配,有 /default/url/style.css 之类的文件,因此删除 = 将导致不提供这些文件。
    【解决方案2】:

    问题出在这里

    location = /default/url {
            rewrite ^/(.*)$/some/path2/index.html;
    }
    

    这会使内部重定向到 / 路径内的 /some/path2/index.html ,因此它会触发 location / 块,该块重定向到 /default/url 和以此类推。

    我的解决方案是制作空块以排除 location /

    中的路径
    location /some/path2/index.html {}
    

    【讨论】: