【问题标题】:.htaccess RewriteEngine converting links without changing links.htaccess RewriteEngine 转换链接而不更改链接
【发布时间】:2014-10-01 12:19:53
【问题描述】:

我正在开始学习 PHP 和 .htaccess 的第一步,我的大部分新网站都是关于主要类别和少数子类别的。 以下是我在开发 .htaccess RewriteEngine 之前的链接示例:

  • example.com/index.php?cat=email
  • example.com/index.php?cat=about&show=some

在 .htaccess RewriteEngine 的帮助下,我将它们转换为:

  • example.com/email/
  • example.com/about/some/

这是 .htaccess 的一部分:

RewriteRule ^([A-Za-z0-9-]+)/$ index.php?cat=$1 [L]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/$ index.php?cat=$1&show=$2 [L]
RewriteRule ^([A-Za-z0-9-]+)$ index.php?cat=$1 [L]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)$ index.php?cat=$1&show=$2 [L]

现在的问题是大多数内容都有内部链接,例如:“example.com/index.php?cat=about&show=some” 全部更改是选项,但无论如何......还有什么可以做的吗?我听说过一些 .htaccess 选项可以将链接自动转换为您需要的格式,而无需手动更改它们,因此 PHP 页面中的所有链接都是相同的,但是一旦用户加载页面,链接就会像(example.com/about/some/ ) 有没有类似的东西,或者有没有其他选项可以保留原始链接而不全部更改?

干杯!

【问题讨论】:

  • 这对您的服务器来说是一种超载,也是一种不好的做法。你应该总是让它思考友好,这样你就只需要规则一次,而不是必须双重重定向以获得正确的结果。您还可以将当前规则恢复为 2 条规则。通过使用?,例如:RewriteRule ^([A-Za-z0-9-]+)/?$ index.php?cat=$1 [L],您将有 2 个规则来完成您需要的所有操作,而不是 4 个,也可以恢复为单个规则,但为了清楚起见,最好使用 2。
  • 干杯!只是改为两行而不是四行: RewriteRule ^([A-Za-z0-9-]+)/?$ index.php?cat=$1 [L] RewriteRule ^([A-Za-z0-9-] +)/([A-Za-z0-9-]+)/?$ index.php?cat=$1&show=$2 [L]

标签: php .htaccess mod-rewrite


【解决方案1】:

您网站上的链接是使用您的 PHP 脚本创建的,使用 htaccess 的 Apache 无法神奇地更改所有这些链接。

现在您可以做的是,使用 htaccess 将旧 URL 重定向到新 URL,并使用 301 重定向。

例如,如果有人单击 example.com/index.php?cat=email,Apache 将重定向(= URL 将更改,并且将有另一个 HTTP 请求)到 example.com/email/,然后将此重写为 index.php?cat=email

将此添加到您的 htaccess 中:

RewriteCond %{REQUEST_FILENAME} index.php$
RewriteCond %{QUERY_STRING} cat=([a-zA-Z0-9-]+)
RewriteRule ^ http://example.com/%1/? [L,R=301]

无论如何,我强烈建议您直接在代码中更改链接,因为即使我刚刚解释的解决方案应该有效(未经测试),但在可以避免重定向时使用重定向并不是很健康。

【讨论】:

  • 我想我只需将 php 中的所有链接更改为 example.com/about/some/ 之类的内容,无论如何感谢您的建议;)
  • 由于某种原因,它给出了错误并且不能使用像 localhost/1/about 这样的转换链接,这是我的 htaccess 的一部分:RewriteEngine On RewriteRule ^([A-Za-z0-9-]+ )/?$ index.php?cat=$1 [L] RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ index.php? cat=$1&show=$2 [L] RewriteCond %{REQUEST_FILENAME} index.php$ RewriteCond %{QUERY_STRING} cat=([a-zA-Z0-9-]+) RewriteRule ^ localhost/1/%1? [L,R=301]
猜你喜欢
  • 2019-09-05
  • 2012-07-31
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 2018-07-24
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多