【问题标题】:Nginx: Only use server block if location matchesNginx:仅在位置匹配时才使用服务器块
【发布时间】:2017-02-20 23:44:22
【问题描述】:

我有一个像这样的捕获所有服务器块:

server {
    listen      80 default_server;
    server_name _;

    location /blog{
        # pass request to ghost
    }
    location /{
        # pass request to custom node app
    }
}

它传递给自定义节点应用程序,该应用程序验证请求的域、协议和路径,并在必要时发出单个 301 重定向;出于 SEO 的目的,我们这样做是为了尽量减少 301 重定向。

我还需要我的 Ghost 博客只能在 https://www.exmaple.com/blog 上提供服务。我添加了以下块:

server {
    listen      80;
    server_name example.com;

    location /blog {
        return 301 https://www.example.com$request_uri;
    }
}

这样对裸域的请求就会被重定向。但是现在对 example.com 的请求会返回默认的 Nginx index.html 页面。我该如何防止呢?我想避免使用if

【问题讨论】:

  • 那么有两个不同的 /blog 您要重定向的位置吗?为什么不将 catch all 位置添加到您的 example.com 服务器块?
  • 我仍然需要裸域上的所有非 /blog 请求才能转到我的自定义节点应用程序。问题是第二个服务器块阻止了这种情况的发生。

标签: redirect nginx


【解决方案1】:

您需要在路由到节点应用程序的裸域服务器块中有一个包罗万象

server {
    listen      80;
    server_name example.com;

    location /blog {
        return 301 https://www.example.com$request_uri;
    }

    location /{
        # pass request to custom node app
    }
}

【讨论】:

  • 所以只是复制整个location / 块?
  • 是的,问题是裸域仅指定位置为 /blog 时要执行的操作。所以设置包罗万象应该能让你工作。
猜你喜欢
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 2017-05-12
  • 2021-01-25
  • 2021-09-05
  • 1970-01-01
相关资源
最近更新 更多