【问题标题】:Rewrite in Subpath 404 urls with Nginx使用 Nginx 重写子路径 404 url
【发布时间】:2019-08-27 14:54:23
【问题描述】:

目前我有一个主要重定向到我的网络服务器的主页。但是,我想在 404 不适用于家庭之后使用重定向来处理子路径,并且对于具有多个子路径的子路径来说是的。那就是不重复规则,我必须处理一个REGEX,但是我不知道如何插入这些规则并返回到当前子路径。

www.foo.com.br

子路径

www.foo.com.br/machine
www.foo.com.br/cloud
www.foo.com.br/air

今天

# define error page
error_page 404 = @notfound;

# error page location redirect 301
location @notfound {
    return 301 /;
}

想要回答 404

www.foo.com.br/machine/test123  

www.foo.com.br/machine/

【问题讨论】:

    标签: nginx nginx-location nginx-config


    【解决方案1】:

    您可以在return 语句之前添加rewrite 规则,以匹配您希望区别对待的特定子目录。

    例如:

    location @notfound {
        rewrite ^/(machine|cloud|air)/. /$1/ permanent;
        return 301 /;
    }
    

    详情请见this document

    【讨论】:

    • 理查德,感谢您的回复。创建的正则表达式如下:error_page 404 = @notfound;    location @notfound {      rewrite ^/([\w-]*)/.* /$1 permanent;    } 如果 url 不存在,则预期结果是第一个字段。它正在工作。但是我还有另一个问题,在进行重定向时,这是从主页下载index.html。你见过这样的事吗?
    • 您可以使用curl -I 测试重定向,但您可能在重写的URI 中缺少尾随/
    • 谢谢,你说得对。我会结案。我意识到做重定向只是获取 * .php 的所有内容,然后是的,一切正常,但如果我尝试使用正常路径 foo.com.br/air/ 不会去,并从主页下载 index .html。我认为是try_files 配置。
    • 理查德,这很棒!谢谢!如果你可以看看,请。 link
    【解决方案2】:

    用于获取第一个字段并在 404 之后重定向的 REGEX:

      error_page 404 = @notfound;
    
      location @notfound {
        rewrite ^/([\w-]*)/.* /$1/ permanent;
    

    在您的 php 块中将 fastcgi_intercept_errors 设置为 on

      location ~ \.php$ {
        include /etc/nginx/fastcgi_params;
        # intercept errors for 404 redirect
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      }
    

    【讨论】:

      猜你喜欢
      • 2018-11-17
      • 2016-11-27
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 2022-11-03
      • 1970-01-01
      相关资源
      最近更新 更多