.htaccess 301 redirection old url to new url with

2019-08-08 06:18发布

问题:

I am facing issue with redirect below URL to new URL with query string.

http://www.mywebsite.co.uk/product-category/subcategory/?id=TEST_TS&fromDate=&parts=

to

http://www.mywebsite.co.uk/product-category/subcategory/test_ts

I need to also query string word into lowercase as well.

Note

  • TEST_TS keyword is the value of the first query string and must be in lowercase.
  • For product-category keyword is fixed
  • For subcategory keyword is dynamic [only characters letters a-z or A-Z]
  • For query string must removed second and third parameter

I have also tried below code in .htaccess as well, But not working for me.

RewriteRule ^product-category/([a-zA-Z0-9-/+]+)/?id=(.*)$&%{QUERY_STRING}   product-category/([a-zA-Z0-9-/+]+)/{lc:$2$} [L]

回答1:

Define this RewriteMap in your VirtualHost section and restart Apache:

RewriteMap lc int:tolower

Then inside site root .htaccess have this code:

RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} (/product-category/subcategory)/?\?id=([^\s&]+) [NC]
RewriteRule ^ %1/${lc:%2}? [R=301,L,NE]

# internal forward from pretty URL to actual one
RewriteRule ^(product-category/subcategory)/(\w-]+)/?$ $1/?id=$2&fromDate=&parts= [L,QSA,NC]

${lc:%2} will convert value in %2 to lowercase.