Question

I need to rewrite urls and redirect the old requests to the new urls permanently. It's important to get the 301 recognized by Google to maintain the indexed pages.

Old Url: example.com/buy-productname-category-item/rest-of-url.html

New Url: example.com/productname-item/rest-of-url.html

Basically removing "buy-" and "category-" from the first part of the url. The rest of the urls all follow the same structure.

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]

Please let me know why the above code is not working and also let me know if the [L,R=301] is actually what I need here.

Était-ce utile?

La solution

You can try this

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

Update

I think if you place the above rewrite statements above your original .htaccess code (after rewriteengine on), it'll map your request to the right page, i.e., /page/page.php with your URL in $_GET['uri'], i.e., [uri] => productname-item/rest-of-url.html. In that page you can parse the URL (like probably you're already doing) and extract the values.

Final .htaccess code

Options +FollowSymLinks
RewriteEngine On


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


# 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top