What the best .htaccess rewrite code to force URL like this one
https://www.example.com/index.php?page=report/tinytoes_mothercare
to that?
https://www.example.com/report/tinytoes_mothercare
My web site already resolve https://www.example.com/report/tinytoes_mothercare
, so I want to avoid any duplicate contents with the ugly and bad URL above.
You can do something like the following at the top of your .htaccess
file, before the existing rewrite (that "resolves" the pretty URL) to redirect the old URL with a query string to your new pretty URL.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^page=([\w/-]*)
RewriteRule ^index\.php$ /%1 [QSD,R=302,L]
The first condition that checks against the REDIRECT_STATUS
environment variable ensures we don't get a redirect loop by redirecting the rewritten URL. REDIRECT_STATUS
is empty on the initial request, so only redirects direct requests from the client.
The second condition gets the necessary value from the query string page
URL parameter. This matches characters a-z
, A-Z
, 0-9
, _
(underscore), /
(slash) and -
(hyphen) - as in your example URL. If you need to match more variation then the character class will need to be expanded. This value is then used in the RewriteRule
substitution string using the %1
backreference.
Note that this is a 302 (temporary) redirect. Only change to a 301 (permanent) when you are sure it works OK, in order to avoid caching issues.