'Redirect dynamic subdomain URL to its dynamic site URL
I need to redirect users with old links to a subdomain to a new link that is dynamically generated using information from the link.
For example:
Old Link will look like this:
subdomain-2013.old-domain.com/data/process/aqs-2d3f4f5g-fgtgyy-uunb.xml
To construct the new link, I need the year provided in the subdomain and the file name. (The year will change, it is not constant).
New Link:
new-domain.com/2013/data/process/aqs-2d3f4f5g-fgtgyy-uunb.xml
How is this done? Is this something accomplished with .htaccess?
Solution 1:[1]
You can do it like this using mod_rewrite near the top of the root .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain-(\d{4})\.(example\.com) [NC]
RewriteRule ^data/process/([a-z0-9-]+\.xml)$ https://%2/%1/$1 [R=301,L]
Where %1 and %2 are backreferences to the preceding CondPattern and $1 is a backreference to the captured group in the RewriteRule pattern.
HOWEVER, I've just noticed you've tagged the question wpengine. The webhost "WP Engine" no longer supports .htaccess config files. Reference: https://wpengine.com/support/htaccess-deprecation/ - UPDATE: Although it seems this tag has since been removed from the question.
UPDATE: If the target domain is different (a later change to the question) then this would need to be hardcoded in the substitution string, replacing the %2 backreference. For example:
RewriteCond %{HTTP_HOST} ^subdomain-(\d{4})\.old-domain\.com [NC]
RewriteRule ^data/process/([a-z0-9-]+\.xml)$ https://new-domain.com/%1/$1 [R=301,L]
The example in the question is passing just the .xml filename to the target URL, it is not passing the preceding URL-path, which is what the rule above is doing.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
