301重定向和URL在同一规则中重写

时间:2014-05-05 13:06:56

标签: php .htaccess mod-rewrite

我需要重写网址并将旧请求永久重定向到新网址。让Google认可301以维护索引页面非常重要。

旧网址:example.com/buy-productname-category-item/rest-of-url.html

新网址:example.com/productname-item/rest-of-url.html

基本上从网址的第一部分删除“买 - ”和“类别 - ”。其余网址都遵循相同的结构。

Options +FollowSymLinks
RewriteEngine On


# this rule sends root requests to index.html, which is then sent by the next rule to /php/page.php 

# sends all requests for .html files to page.php for service
RewriteCond %{REQUEST_URI} !(.*)/sitemap.xml
RewriteCond %{REQUEST_URI} !(.*)/xml
RewriteCond %{REQUEST_URI} !(.*)/mockups
RewriteCond %{REQUEST_URI} !(.*)/php
RewriteCond %{REQUEST_URI} !(.*)/rss
RewriteRule ^(.*).html$ /php/page.php?uri=$1 [NC]
### ^ the most important rule

#---- remove buy- and ABC from urls
# the uri is being changed and page.php can't find it so it handles it as 404
RewriteRule buy-(.+)-ABC-123/(.+)$ /$1-123/$2 [L,R=301]

请让我知道为什么上面的代码不起作用,如果[L,R = 301]实际上是我需要的话,请告诉我。

1 个答案:

答案 0 :(得分:1)

你可以试试这个

RewriteEngine On
RewriteBase / #modify rewrite base according to your directory structure
RewriteRule buy-(.+)-category-(.+)/(.+)$ /$1-$2/$3 [L,R=301]

<强>更新

我认为如果您将上述重写语句置于原始.htaccess代码之上(在重写启动之后),它会将您的请求映射到正确的页面,即/page/page.php将您的网址放在{{ 1}},即$_GET['uri']。在该页面中,您可以解析URL(可能就像您已经在做的那样)并提取值。

最终.htaccess代码

[uri] => productname-item/rest-of-url.html