【问题标题】:htaccess physcially redirect in case of 404htaccess 在 404 的情况下进行物理重定向
【发布时间】:2012-02-22 03:49:10
【问题描述】:

首先,当页面不存在时,我知道如何简单地重定向到 404

ErrorDocument 404 /index.php

我想要做的是物理重定向到索引页面。因此,如果用户输入mydomain.com/abc 并且该页面不存在,它会实际重定向到索引页面。我不希望 url 与错误地址保持相同。是的,我知道这没什么大不了的,但它困扰着我。我可以通过将自定义 404 页面重定向到主页来完成此操作,但我不希望这样做。

我已经用[R] 重定向标志尝试过这个,显然它不起作用。

Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]
RewriteRule ^(.*)$ /index.php [L,R]

更新

这是我得到的错误,它将网址重写为mydomain.com/index.php

我尝试仅使用/ 删除index.php,但它没有重定向,但在下面给出了相同的错误。

The page isn't redirecting properly         

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

This problem can sometimes be caused by disabling or refusing to accept
cookies.

【问题讨论】:

  • 发生了什么?你的重写规则看起来不错。
  • 不要更新问题中的答案。人们不会费心往下看。现在我已经删除了答案部分。
  • @ThinkingMonkey 好吧,您的回答并不完全正确。您的回答允许mydomain.com/rates.phpasfasfasdf。这就是我发布我所做的事情的原因。
  • 如果 /rates.phpasfasfasdf 不是有效的文件/目录,它将重定向到 index.php。你想发生什么?
  • @ThinkingMonkey 我打错了我的评论mydomain.com/rates.php/asfasf 没有重定向到index.php

标签: .htaccess mod-rewrite redirect


【解决方案1】:

这样做:

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} !(?:\.\w+)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ([^/]+)/?$ $1.php 

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ / [L,R]

说明:

检查文件是否有扩展名:

RewriteCond %{REQUEST_URI} !(?:\.\w+)$ [NC]

如果没有,检查文件是否存在:

RewriteCond %{REQUEST_FILENAME} !-f

如果不是文件,则检查它是否是存在的文件夹:

RewriteCond %{REQUEST_FILENAME} !-d

如果不附加.php。如果 / 出现在末尾,请将其删除并附加 .php

RewriteRule ([^/]+)/?$ $1.php 

检查附加的.php 或任何扩展文件是否实际上是存在的文件:

RewriteCond %{REQUEST_FILENAME} !-f

检查是否为目录:

RewriteCond %{REQUEST_FILENAME} !-d

如果不是,那么它是一个无效的文件请求并将其重定向到/ 重写规则 ^(.*)$ / [L,R]

【讨论】:

  • 完美运行。没想到我必须为另一条规则重做RewriteCond。我已经在我的问题中添加了我所拥有的工作
  • 由于这不能完全从我的角度工作,我将重新打开它。如果一段时间后没有人能够回答这个问题,我会再次接受你的回答。
【解决方案2】:

这应该是您基于 mod_rewrite 的 404 处理:

# if it is not a file, directory or link
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ index.php [L,R]

但是我不确定你在第一条规则中做了什么?您是否尝试将 .php 添加到每个请求 URI?

【讨论】:

  • 不,第一条规则是从 url 中删除 .php 扩展名,这样他们就不必输入 mydomain.com/test.php 他们只需输入 mydomain.com/test
  • 好的,然后保留该规则并在最后附加我的规则以获得 404 重定向。
  • 这将导致无限循环仅当 /index.php 不存在时。请在您的问题中发布来自 access.log 和 error.log 的匹配条目。
  • 我正在使用 godaddy 托管,但在获取任何日志信息时遇到了一些问题。我会尽快得到它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多