如何在修改 nginx $args 并重定向到 Wordpress 中修改后的 URL 后修复 404 错误

How to fix 404 Error after modifying nginx $args and redirecting to modified URL in Wordpress

背景: 我们使用重定向到我们 Wordpress 网站上的确认页面的外部服务。此服务通过 URL-strings 发送某些我们想要删除的参数,因为它们包含私人信息。不幸的是,服务在那个方向上是不可配置的(i.a。它总是会发送全套参数)。

Objective: 我目前正在处理一个 nginx 位置块,它应该从请求中剥离某些 URL-Parameters 到某个页面,并使用 "clean" URL 重定向到同一页面。到目前为止,我已经设法摆脱了 URL 中不需要的参数,但是,我正在努力处理位置块的重写部分。看来我还没有弄清楚如何在 Wordpress 上下文中正确重写 URL。

错误描述: 当使用参数 ?full_name=john 访问所需的 URL 时,nginx 正确地剥离参数并尝试重定向到页面。但是,nginx 抛出 404 错误。

环境:

代码: 我使用了 Siwei Shen 对 Remove parameters within nginx rewrite 的评论作为开始。 这是我目前所拥有的:

location ^~ /confirmation/ {

    if ($request_uri ~ "([^\?]*)\?(.*)full_name=([^&]*)&?(.*)") {
        set $original_path ;
        set $args1 ;
        set $unwanted ;
        set $args2 ;
        set $args "";

        rewrite ^(.+)$ /index.php/$original_path?$args1$args2 permanent;
    }
}

我认为罪魁祸首是 rewrite ^(.+)$ /index.php/$original_path?$args1$args2 permanent; 因为我最不确定如何重写这个 Wordpress 友好的。

非常感谢任何帮助或正确方向的指示。非常感谢!


更新 2019-07-05

感谢@RichardSmith,我修改了代码:

location ^~ /confirmation/ {

    if ($request_uri ~ "([^\?]*)\?(.*)full_name=([^&]*)&?(.*)") {
        set $original_path ;
        set $args1 ;
        set $unwanted ;
        set $args2 ;
        set $args "";

        rewrite ^(.+)$ $original_path?$args1$args2 permanent;
    }
}

这会导致 404 错误(取自 proxy_error_log):

2019/07/05 11:51:13 [error] 22623#0: *39709 "/var/www/vhosts/domain.de/sub.domain.de/confirmation/index.html" is not found (2: No such file or directory), client: 109.41.XXX.XXX, server: sub.domain.de, request: "GET /confirmation/ HTTP/2.0", host: "sub.domain.de"

这看起来像是有意为之的行为,因为该位置没有 index.html。但是,现在我必须告诉 nginx 不要将 index.html 附加到重写的请求中。

你知道如何完成这个吗? 提前致谢!


解决方案:

我的问题的解决方案是我缺少一个语句来告诉 nginx 在找不到文件时如何工作。所以nginx在那个地方找index.html,没找到。在 URL 重写之后添加一个额外的 if() 块来处理没有文件的位置访问就可以了。

代码:

location ^~ /confirmation/ {

    if ($request_uri ~ "([^\?]*)\?(.*)full_name=([^&]*)&?(.*)") {
        set $original_path ;
        set $args1 ;
        set $unwanted ;
        set $args2 ;
        set $args "";

        rewrite ^(.+)$ $original_path?$args1$args2 permanent;
    }
    if (!-e $request_filename) {
        rewrite / /index.php last;
    }
}

解决方案:

我的问题的解决方案是我缺少一个语句来告诉 nginx 在找不到文件时如何工作。所以nginx在那个地方找index.html,没找到。在 URL 重写之后添加一个额外的 if() 块来处理没有文件的位置访问就可以了。

代码:

location ^~ /confirmation/ {

    if ($request_uri ~ "([^\?]*)\?(.*)full_name=([^&]*)&?(.*)") {
        set $original_path ;
        set $args1 ;
        set $unwanted ;
        set $args2 ;
        set $args "";

        rewrite ^(.+)$ $original_path?$args1$args2 permanent;
    }
    if (!-e $request_filename) {
        rewrite / /index.php last;
    }
}