如何在不发送 404 标头的情况下重定向找不到的 URL? [英] How do I redirect a URL that isn't found without sending a 404 header?
问题描述
我的网站需要一个 .htaccess
文件,当找不到页面时,该文件会将用户重定向到 index.php
.但是,我不希望 Apache 随文档一起发送 404 标头.
My website needs a .htaccess
file that will redirect a user to index.php
when a page is not found. However, I do not want Apache to send a 404 header with the document.
我之前问过这个问题:Apache .htaccess 404 错误重定向
命令 "ErrorDocument/index.php"
产生了我想要的确切效果,除了它发送带有页面的 404 标头.我能做什么?我应该用 PHP 覆盖 404 标头吗?
The command "ErrorDocument /index.php"
produces the exact effect that I want, except that it sends a 404 header with the page. What can I do? Should I overwrite the 404 header with PHP?
推荐答案
将此添加到您的 .htaccess
文件中:
Add this to your .htaccess
file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
- 启用重写
- 检查请求的文件是否作为具有大小(非空)的常规文件存在
- 检查请求的文件是否为链接
- 检查请求的文件是否是目录
- 如果前 3 条语句之一为真,则显示该文件
- 否则转到 index.php
如果重定向到 index.php,您可以通过在 index.php
If the redirect to index.php happens u can get the requested uri by using $_SERVER["REQUEST_URI"]
inside index.php
- '-d' (is directory) 将 TestString 视为路径名并测试是否它存在并且是一个目录.
- '-f'(是常规文件)将 TestString 视为路径名并测试是否它存在并且是一个普通文件.
- '-s'(是具有大小的常规文件)将 TestString 视为路径名并测试它是否存在并且是一个大小大于的常规文件零.
- '-l'(是符号链接)将 TestString 视为路径名并测试是否它存在并且是一个符号链接.
- '-F'(是通过子请求的现有文件)检查 TestString 是否为有效文件并可通过所有服务器当前配置的访问该路径的控件.这使用一个内部子请求来确定检查,所以小心使用它,因为它降低您的服务器性能!
- '-U'(是通过子请求的现有 URL)检查 TestString 是否为有效的 URL 并可通过所有服务器当前配置的访问该路径的控件.这使用一个内部子请求来确定检查,所以小心使用它,因为它降低服务器的性能!
更多信息:http://httpd.apache.org/docs/current/mod/mod_rewrite.html
这篇关于如何在不发送 404 标头的情况下重定向找不到的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!