6

This htaccess snippet is supposed to redirect

myhost.com/?p=1&preview=true

to

alt.myhost.com/?p=1&preview=true

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^myhost.com$ [NC]
RewriteRule ^/\?p=([0-9]+)&preview=true$ http://alt.myhost.com/?p=$1&preview=true [NC,R=301,L]

but for some reason I can't escape the / and ? part of the URL. Not sure why this isnt working...

I've tried escaping ?

\\? \? [?]

and I've tried escaping the /

\\/ \/ [/]

none of these seem to work either...

help!

qodeninja
  • 2,723
  • 10
  • 31
  • 33
  • `RewriteRule` does not work with query strings (everything after `?`) only with url path (which you basically do not have in your example). Are you trying to redirect **ALL** URLs from one domain to another or just this one? – LazyOne Jun 13 '11 at 18:36
  • Just the one =/ – qodeninja Jun 23 '11 at 18:36

2 Answers2

9

This will redirect ALL requests from myhost.com to alt.myhost.com

RewriteCond %{HTTP_HOST} !^alt\.myhost\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) http://alt.myhost.com/$1 [L,R,NE]

Code taken from official mod_rewrite manual

If for whatever reason the query string is not get preserved, replace the last line by

RewriteRule ^/?(.*) http://alt.myhost.com/$1 [L,R,NE,QSA]

UPDATE: This will redirect your specific URL to another domain:

RewriteCond %{HTTP_HOST} =myhost.com [NC]
RewriteCond %{QUERY_STRING} ^(p=1&preview=true)
RewriteRule ^$ http://alt.myhost.com/?%1 [R=301,L]
LazyOne
  • 3,014
  • 1
  • 16
  • 15
7

Because of the query string "p=([0-9]+)&preview=true" I guess your need for a redirect is due to having wordpress admin on a subdomain and the website on your main domain.

Because of that you can't preview drafts.

I came up with a broader solution that also works with custom post types and plugins that add parameters:

RewriteCond %{HTTP_HOST} =myhost.com [NC]
RewriteCond %{QUERY_STRING} (preview=true)
RewriteRule ^$ http://alt.myhost.com/?%{QUERY_STRING} [R=301,L]

In plain english when "preview=true" is found in a query, the redirection happen to the alt subdomain and the full query is kept.

  • Hi, this is brilliant. Would this work for postname permalinks too? – panza Feb 01 '17 at 22:58
  • Solution is great but it preview value is "truee" or "truenotsotrue", this thing still works when it shouldn't be. In other words, it doesn't match EXACT query string value – Suleman Feb 20 '20 at 00:38