nginx 重定向目录(包括 php 文件)

nginx 重定向目录(包括 php 文件)

以前我的网站 URL 是这样的:

现在 URL 如下:

我正在使用以下内容:

location /forums/ {
    rewrite ^/forums/(.*)$ https://www.example.com/$1 permanent;
}

并且它正确地重定向了类型 1 的 URL,但是类型 2 之类的 URL 返回了 404。我怎样才能让 nginx 也重定向 php 文件?谢谢!

答案1

您遇到此问题的原因是因为location正则表达式定义的指令优先且具有最终决定权,因此,您可能让您的location ~ \.php$处理程序处理该请求。

按照http://nginx.org/r/location你应该做的就是添加^~修饰符对于现有代码,不检查正则表达式,如下所示:

location ^~ /forums/ {
    rewrite ^/forums/(.*)$ https://www.example.com/$1 permanent;
}

另一个考虑因素是,尽管(和指令$uri后面的变量)locationrewrite不含$is_args$args(因此,$1在上面的例子中也没有),它们仍然会被自动添加到上下文中rewrite,按照http://nginx.org/r/rewrite,因此,不需要对上面的代码进行任何其他操作。


作为奖励,仍然可以进行与维护相关的优化 - 即,您实际上不必明确指定https(或$scheme)和主机,而是可以让 nginx 根据上下文找出答案。

另外,正如http://nginx.org/docs/http/ngx_http_rewrite_module.html#internals/,您可以通过使其成为捕获的一部分来节省额外的指令。

因此,通过上述两种优化,最适合您的情况的方法可能是:

location ^~ /forums/ {
    rewrite ^/forums(/.*)$ $1 permanent;
}

以下是上述代码,用于确认$scheme://$host(和:$server_port,仅在需要时)会自动添加,具体设置请参阅http://nginx.org/r/absolute_redirect

% curl -i "localhost:4441/forums/showthread.php?t=123" |& fgrep Location
Location: http://localhost:4441/showthread.php?t=123
%

相关内容