Search code examples
.htaccessmod-rewritehttp-status-code-301

htaccess 301 redirect dynamic url


I am moving my site to new domain. Need to redirect pages
from
old-site.com/oldpage.php?id=X
to
new-site.com/newpage-X
(X is number)

Why this rule does not work?

RewriteEngine on
RewriteRule ^oldpage.php?id=(.*)$ http://new-site.com/newpage-$1 [R=301,L]

Solution

  • The RewriteRule does only operate on the URL path and not the URL query. You need to use the RewriteCond directive to test the URL query (%{QUERY_STRING}). So try this rule:

    RewriteCond %{QUERY_STRING} ^(([^&]*&)*)id=([^&]+)&?(.*)?$
    RewriteRule ^oldpage\.php$ http://new.example.com/newpage-%3?%1%4 [L,R=301]
    

    This rule will also preserve other parameters in the query.