Search code examples
.htaccessrequest-uri

Difficult to alter and separate REQUEST_URI with htaccess


I'm trying to treat a URL with htaccess and %{REQUEST_URI} parameter. I researched a lot, use htaccess.madewithlove.be and a virtual machine to build the rule and test without success.

The Request URL is:

1) www.example.com.br/category/product/Beer?id=16

Anothe example of requested URL to better understanding:

2) www.example.com.br/category/product/Wine?id=33

The rule I created is:

RewriteCond %{HTTP_HOST} ^(.*)example\.com\.br$
RewriteCond %{REQUEST_URI} ^(.*)category/product/(.*)$
RewriteRule ^(.*)$ http://www.mynewsite.com.br/category/product/luxe-product/$1? [R=301,L]

The expected rewrite are:

1) www.mynewsite.com.br/category/product/luxe-product/Beer

2) www.mynewsite.com.br/category/product/luxe-product/Wine

But, using this rule the output URL are:

1) www.mynewsite.com.br/category/product/luxe-product/category/product/Beer

2) www.mynewsite.com.br/category/product/luxe-product/category/product/Wine

In this case I put hardly category/product in the output to simplify since I couldn't separate using $0, $1 and $2 directives. Anyone has a idea how to solve this?

Regards,


Solution

  • You don't need a condition on REQUEST_URI since you can match it in RewriteRule.

    Instead, you can use this rule

    RewriteCond %{HTTP_HOST} example\.com\.br$ [NC]
    RewriteRule ^category/product/([^/]+)$ http://www.mynewsite.com.br/category/product/luxe-product/$1? [R=301,L]
    

    Or you could use REQUEST_URI like you did (both are correct)

    RewriteCond %{HTTP_HOST} example\.com\.br$ [NC]
    RewriteCond %{REQUEST_URI} ^/category/product/([^/]+)$ [NC]
    RewriteRule ^ http://www.mynewsite.com.br/category/product/luxe-product/%1? [R=301,L]