Since you have changed the URL (and changed the domain) this would need to be an external "redirect", as opposed to a "rewrite" (or "forward") since you need to redirect the user/search engine/bot.
I am assuming that old-domain.com
and new-domain.com
point to different servers. If not then you'll need an additional condition (RewriteCond
directive) that checks the requested hostname (HTTP_HOST
).
If the URLs would be only old-domain.com/deceased-persons-2021 OR only old-domain.com/deceased-persons/?id=1500_betty-white, I knew the solutions.
I would have thought that if you knew how to do these redirects separately then you would know how to do them together since you basically just combine them, so it would have been interesting to see how you would have solved these separately.
Capturing part of the URL-path (ie. 2021
) from the RewriteRule
pattern generates a backreference of the form $n
(where n
is a number 0-9). Whereas capturing part of the query string (which requires a preceding condition) generates a backreference of the form %n
. You then use $n
and %n
in the substitution string.
For example:
# /deceased-persons-2021 to /deceased-persons/2021 RewriteRule ^deceased-persons-(\d{4})$ https://new-domain.com/deceased-persons/$1 [R=301,L]
The $1
backreference contains the captured 4-digit year from the end of the URL-path.
# /deceased-persons/?id=1500_betty-white to /deceased-persons/betty-white RewriteCond %{QUERY_STRING} ^id=\d+_([a-z-]+)$ RewriteRule ^deceased-persons/$ https://new-domain.com/deceased-persons/%1 [QSD,R=301,L]
The %1
backreference contains the captured name from the preceding condition (RewriteCond
directive). In this example, the name part can only contain lowercase letters a-z and hyphens.
The QSD
flag is necessary to discard the original query string.
Combining these two rules...
# /deceased-persons-2021/?id=1500_betty-white to /deceased-persons/2021/betty-white RewriteCond %{QUERY_STRING} ^id=\d+_([a-z-]+)$ RewriteRule ^deceased-persons-(\d{4})/$ https://new-domain.com/deceased-persons/$1/%1 [QSD,R=301,L]
Personally, I would also capture the deceased-persons
part of the URL-path to avoid repetition. For example:
RewriteCond %{QUERY_STRING} ^id=\d+_([a-z-]+)$ RewriteRule ^(deceased-persons)-(\d{4})/$ https://new-domain.com/$1/$2/%1 [QSD,R=301,L]
This rule would need to go at the top of the root .htaccess
file at old-domain.com
.
This assumes that the name (in the query string) consists of just lowercase letters and hyphens. If, however, there can be "an additional digit in the slug" then you'll need to modify the regex accordingly.
Test first with a 302 (temporary) redirect to avoid potential caching redirect and only change to a 301 when you have confirmed this works as intended. 301 (permanent) redirects are cached persistently by the browser so can make testing problematic.