2

基本上我在我的网站上工作是为了对 SEO 友好。我想实现以下目标:

  • 将 url 重写为漂亮的
  • 删除多个斜杠(example.com/////something///例如example.com/something/
  • 将 www 版本重定向到非 www 版本。
  • 隐藏所有 url 中的 index.php 文件
  • 从旧网址重定向(/?id=something/到新网址/something/

我想出了这段.htaccess代码:

RewriteCond %{THE_REQUEST} //
RewriteRule .* $0 [R=301]

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteCond %{QUERY_STRING} ^id=([a-z0-9\/-]+)
RewriteRule ^(.*)$ http://example.com/%1? [R=301]

RewriteRule ^index.php(.*)$ /$1 [R=301]
RewriteRule ^([a-z0-9\/-]+)$ /?id=$1 [L] 

...虽然它正在工作,但它有一个副作用:链重定向,例如。example.com/?id=something//////-> example.com/something//////->example.com/something/

那么有没有办法重写或修改此代码,以便它只重定向一次到 URL 的首选版本?

4

2 回答 2

1

试图解释你想要什么,让我们看看你问题中的规则:

.1 无法理解这样做的目的:

RewriteCond %{THE_REQUEST} //
RewriteRule .* $0 [R=301]

.2 您问题中的此规则集删除www查询字符串并将其转换?id=val/val,但仅当传入的 URI 具有www并且存在查询字符串时,因为必须满足两个条件:

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteCond %{QUERY_STRING} ^id=([a-z0-9\/-]+)
RewriteRule ^(.*)$ http://example.com/%1? [R=301]

.3 本规则

RewriteRule ^index.php(.*)$ /$1 [R=301]

隐藏index.php,但仅当它位于根目录时。例子:

http://www.example.com/index.php?id=val

当它在子目录中时不起作用。例子:

http://www.example.com/folder/index.php?id=val

.4 无法理解这样做的目的:

RewriteRule ^([a-z0-9\/-]+)$ /?id=$1 [L]

我建议这样做:

RewriteEngine On
RewriteBase /

#Redirects all www to non-www
RewriteCond %{HTTP_HOST} www\.example\.com$ [NC]
RewriteRule ^(.*)/?$ http://example.com/$1 [R=301,L]

#Hides "index.php" keeping the query if present
RewriteRule ^(.*)/index\.php$ $1/ [R=301,QSA,L]

#Converts query string `?id=val` to `/val`
RewriteCond %{QUERY_STRING} id=([^/]+)
RewriteRule .* /%1? [R=301,L]
于 2012-12-29T03:58:18.133 回答
1

请记住,蜘蛛会在几个月后“适应”正确的新结构,而且问题最终可能比最初看起来要严重得多。您可以保留所有 .htaccess 代码,知道它总是在那里纠正任何“旧”引用,但实际上几乎不会真正使用。

当“修复”URL 以某种规范形式时,我从来没有找到一种简单的方法来避免多次往返返回客户端。mod_rewrite 似乎更关注“本地”重定向情况,客户端不知道它返回的内容来自与 URL 所暗示的不完全匹配的文件结构。

可以在本地保存所有 URL 模块,然后通过将所有内容设置在新创建的“环境”变量中,然后在最后询问基本上“有什么改变?” 然而,这样做非常冗长,相当笨拙,而且很容易出错,并且从未成为“推荐的技术”。

于 2015-09-06T19:56:28.587 回答