Purushotam Sharma
Purushotam Sharma

Reputation: 191

How to redirect URL using .htaccess with dynamic parameter?

I want to redirect

https://example.com/product-info/A100001

to

https://example.com/product-info/index/index/id/A100001

using htaccess redirect rule

A100001 will be dynamic like

A100001
A100002
A100003
A100004
....

I am trying this

RewriteEngine on
RewriteCond %{QUERY_STRING} product-info/A100001
RewriteRule ^$ /routing/index/index/id/? [L,R=301]

Source

Also tried other example but not working in my scnario

Anyone who expert in htacees rules can help me in this.

Upvotes: 0

Views: 150

Answers (1)

MrWhite
MrWhite

Reputation: 45829

RewriteCond %{QUERY_STRING} product-info/A100001
RewriteRule ^$ /routing/index/index/id/? [L,R=301]

Your example URL contains a URL-path only, it does not contain a query string. The rule you've posted would redirect /?product-info/A100001 to /routing/index/index/id/.

Try something like the following instead:

RewriteRule ^(product-info)/(A\d{6})$ /$1/index/index/id/$2 [R=302,L]

The above would redirect a request of the form /product-info/A123456 to /product-info/index/index/id/A123456.

The $1 backreference simply contains product-info, captured from the RewriteRule pattern (saves repitition) and $2 contains the dynamic part (an A followed by 6 digits).

This is a 302 (temporary) redirect. Always test first with a 302 to avoid potential caching issues.

The order of directives in your .htaccess file is important. This rule will likely need to go near the top of the file, before any existing rewrites.


UPDATE:

redirection is working with your code, Can you please let me know the parameter pattern, I need the number from A452218 to A572217

Regex does not handle numeric ranges, only character ranges. If you specifically only want to match numbers in the stated range then you would need to do something (more complex) like this:

RewriteRule ^(product-info)/A(45221[89]|4522[2-9]\d|452[3-9]\d{2}|45[3-9]\d{3}|4[6-9]\d{4}|5[0-6]\d{4}|57[01]\d{3}|572[01]\d{2}|57220\d|57221[0-7])$ /$1/index/index/id/A$2 [R=302,L]

NB: The $2 backreference now only contains the dynamic number, less the A prefix, which is now explicitly included in the substitution string.

Upvotes: 1

Related Questions