我正在尝试更新我的.htaccess文件,目标是将所有响应"找不到404文件"错误的页面重写到另一个url。
示例:我有这3个链接:
404:domain.com/category/123-article-name.html
工作:domain.com/static-page/10-ways-to-destroy-your-webpage.html
未受影响:domain.com/simple-website.html
在这种情况下,第一个链接应该重定向到domain.com/lost/123 article-name.html,第二个是allready。第三个环节永远不应该受到我的规则的影响。
希望你们能帮助我。这对我来说真的很难解决!非常感谢。
编辑:
RewriteRule ^(.*)/([0-9]+)-(.+).html$ lost/$2-$3.html [L]
这就是我到目前为止所得到的,但这个规则有点"愚蠢",因为它不会测试请求的页面是否存在。
您的规则和CMS的规则是互斥的。
第41行(您的规则)将只在文件存在的情况下执行,因为如果文件不存在(第38行和第39行的rewriteConds),则服务器将尝试返回index.php?page=path_name
,这将生成404错误。
如果你知道丢失的类别/目录的名称,根据第10行到第35行,那么你可以将你的规则应用于其中包含它们的URL。
RewriteRule ^(Ausbildung|Ausland|Berufswelt)/(?=.+-)(.+).html$ lost/$2.html
原始答案
您可以通过添加重写条件来测试文件或目录是否存在
RewriteCond %{REQUEST_FILENAME} !-f # True if the request isn't a file
RewriteCond %{REQUEST_FILENAME} !-d # True if the request isn't a directory
RewriteRule ^.*/([0-9]+)-(.+).html$ lost/$2-$3.html [L]
#not I removed the first capture group because it is unnecessary.
旁注:在您的示例中,由于+
在正则表达式中是贪婪的,因此domain.com/category/123-article-name.html 的捕获组
- 123条
- 名称
这很有效,但可能会人为地约束你。你可以改变规则,包括积极的前瞻:
RewriteRule ^.*/(?=.+-)(.+).html$ lost/$1.html
如果发现至少一个-
,(?=.+-)
告诉正则表达式引擎为任意数量的字符创建匹配
你应该看看这个htaccess测试,它太棒了!