【问题标题】:htaccess url rewrites and redirects not workinghtaccess url重写和重定向不起作用
【发布时间】:2015-09-06 20:40:46
【问题描述】:

我有一个已更新的网站。我想让旧的 url 工作,我想重定向其中的一些,所以来自 google 搜索的链接仍然有效,并使用 .htaccess 重写其他 url 的 url。

例如:

  • 一个重写是 a.com/services 到 a.com/consultancy
  • 一个重定向是 a.com/services/a/b 到 a.com/consultancy

一个额外的复杂情况:站点将每个请求都发送到 /index.php,因为 URL 不是物理文件,但 index.php 脚本使用请求的路径进行内部路由,以提供正确的内容。

我不确定是否可以在同一个 htaccess 中进行重写(服务->咨询)然后再进行一次重写(咨询->index.php)。

尝试这个,我收到任何 URL 的内部服务器错误 500:

RewriteEngine On

#NEW
RewriteCond %{REQUEST_URI} ^services$ [NC]
RewriteRule ^services$ consultancy [L]

#LEGACY
RewriteRule (.*) ./index.php

也尝试了 Redirect 301 指令但没有运气,同样的错误 500。

关于如何混合重写、重定向和最终重写到 index.php 的任何想法?

谢谢!

更新

对于重定向和重写的组合,我意识到一些规则与我原来的问题有点不同,这些可能会导致问题,这里是一个例子:

# Redirect to show "consultancy" in the URL
RewriteRule ^services/a/b?$ consultancy [QSA,R,L,NC]

# If "consultancy" is in the URL, change it to the real path
# "consultancy" is an alias of the path that should be processed by index.php
RewriteRule ^consultancy/?$ en/consultoria [NC]

# Should get the "en/consultoria" path
RewriteRule ^ ./index.php [L]

上一个例子的问题是我得到了重定向 "services/a/b" -> "consultancy" OK,但是重写 "consultancy" -> "en/consultoria" 没有完成。

有什么想法吗?

【问题讨论】:

  • 500 是内部服务器错误,请查看您的错误日志以获取更多信息
  • 如果您将RewriteRule (.*) ./index.php 更改为RewriteRule (.*) index.php,它将解决您的错误500。Request exceeded the limit of 10 internal redirects due to probable configuration error. 是我在您的配置日志中的错误。总的来说,您可能希望确保对 index.php 的请求也不会被重写。
  • 谢谢@MarkusAO 你看到了哪些日志? apache 错误日志?
  • @PabloPazos 是 .htaccess 中的错误,因为它们是 Apache 指令,将记录在 Apache 错误日志中。

标签: php apache .htaccess mod-rewrite redirect


【解决方案1】:

你可以使用:

RewriteEngine On

#rewrite
RewriteRule ^services/?$ consultancy [L,NC]

#redirect
RewriteRule ^services/a/b/?$ consultancy [L,NC,R=302]

#LEGACY
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

【讨论】:

  • 感谢@anubhava,它适用于 /services 的重写,但也在我需要重定向的情况下进行重写。重写不会发出重定向。对于重定向,URL 应该从 /services/a/b 更改为 /consultancy,状态为 302 或 301(实际上这是 301)。我尝试了重定向指令,但它对我不起作用。我读过 Redirect 和 RewriteRule 不能很好地配合使用,并且找不到一个使用两者的 htaccess 文件的示例。有什么想法吗?
  • 谢谢@anubhava,请看我的更新,有一条规则重定向“目标”应该匹配重写“源”,因为它是真实路径的别名。重定向已完成,但未重写。
  • 但是重写 "consultancy" -> "en/consultoria" 没有完成 你怎么知道的?试试:RewriteRule ^consultancy/?$ en/consultoria [NC,L]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-28
  • 1970-01-01
  • 2015-07-28
  • 2015-02-03
  • 2014-08-08
  • 2011-07-05
  • 1970-01-01
相关资源
最近更新 更多