如何使用 .htaccess 重定向到 404 但在地址栏上保留错误的 URL

问题描述

使用 .htaccess,我尝试重定向final class viewmodel: ObservableObject { @Published private(set) var first = 0 @Published private(set) var second = 0 private var subscriptions: Set<AnyCancellable> = [] func start() { Timer.publish(every: 1,on: .main,in: .common) .autoconnect() .scan(0) { accumulated,_ in accumulated + 1 } .assign(to: \.first,on: self) .store(in: &subscriptions) Timer.publish(every: 2,_ in accumulated + 1 } .assign(to: \.second,on: self) .store(in: &subscriptions) } func stop() { subscriptions.removeAll() } } struct ContentView: View { @StateObject private var viewmodel = viewmodel() var body: some View { vstack { Text(String(describing: viewmodel.first)) Text(String(describing: viewmodel.second)) } .onAppear { viewmodel.start() } .ondisappear { viewmodel.stop() } } } ,并在我的网站上遵循以下规则运行正常

404

但正如预期的那样,这也会更改/重定向 URL。例如,如果没有名为 RewriteEngine ON ErrorDocument 404 thedomain.com/404 RewriteCond %{REQUEST_URI} !\.PHP/?$ [NC] RewriteCond %{REQUEST_FILENAME}.PHP -f RewriteRule ^(.*)$ $1.PHP [QSA,L] 文件名,则 URL 将重定向dummy.PHP

如何保留现有 URL (thedomain.com/404) 并重定向thedomain.com/dummy,就像 wordpress 404 页面中发生的情况一样。

enter image description here

解决方法

让您的 .htaccess 代码如下:

RewriteEngine On

ErrorDocument 404 /2021/404.php

RewriteCond %{DOCUMENT_ROOT}/2021/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

当您在 ErrorDocument 404 中有绝对 URL 时,它将执行完全重定向。但是,使用相对 URL 只会进行内部重写以防止 URL 在浏览器中更改。

确保在测试前清除浏览器缓存。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...