Mod_Rewrite: Testing URL got indexed in Google - How do I create a proper 301 redirect?
-
27-09-2019 - |
Question
I worked on a website for which I had a "development URL" that looked something like this:
www.example.com.php5-9.dfw1-2.example.com/
Now, several weeks after the website launch, there is at least one page of content indexed on Google with that URL.
Question: How do I redirect all requests from that test URL to reroute to the actual domain?
So, for instance, I would want:
www.example.com.php5-9.dfw1-2.example.com/page-name
To go to:
www.example.com/page-name
The website is powered by WordPress and hosted on a PHP server. I've experimented with .htaccess without much success.
Solution
If www.example.com is ought to be the only valid host name on your server, you can use this rule to force this host name:
RewriteCond %{HTTP_HOST} !^(www\.example\.com|)$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.example.com%{REQUEST_URI} [L,R=301]
Otherwise try this rule to redirect just this specific host name:
RewriteCond %{HTTP_HOST} =www.example.com.php5-9.dfw1-2.example.com
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.example.com%{REQUEST_URI} [L,R=301]
You might additionally check the request method in REQUEST_METHOD since this rule will match any method (GET as well as POST).
OTHER TIPS
Considering that your primary motivation for this issue is the fact that Google indexed your pages on the test server, I believe that trying to use the mod_rewrite
functionality to keep those links active is a bit redundant (and fiddly).
Instead, I would suggest using Google's Webmaster Tools, and register under both the testing location and the production location. You should then be able to request the URLs under the Testing Subdomain be removed, and also request the Production URL to be crawled (thereby removing the Test links and replacing them with Production links).