.htaccessduplicate-content

How to prevent duplicate content using htaccess


I'm using a .htaccess to create a clean URL but when I checked my site example.com/some-request it has duplicate content with xyz.com/product_view.php?category_id=some-request

I'm finding hard how to fix this and this is my rewrite rule:

RewriteEngine on

RewriteBase /

RewriteRule ^([0-9a-zA-Z_-]+)$ product_view.php?category_id=$1 [NC,L]

What can be a better solution for this?


Solution

  • You need to externally redirect requests for
    example.com/product_view.php?category_id=some-request
    to xyz.com/some-request before your internal rewrite.

    Try the following:

    RewriteEngine on
    RewriteBase /
    
    # Redirect direct requests for the real URL to your desired URL
    RewriteCond %{THE_REQUEST} \?category_id=([^\ ]*)
    RewriteRule ^product_view\.php /%1? [R=301,L]
    
    # Existing rewrite to real URL
    RewriteRule ^([0-9a-zA-Z_-]+)$ product_view.php?category_id=$1 [NC,L]
    

    Bit of an aside... but it's only really duplicate if these URLs get indexed. If you have always linked to your "pretty" URL then the risk is relatively low. This can also be avoided by setting the appropriate rel="canonical" link element on your pages.