Rewrite all URLs to a new domain and include an ex

2019-09-20 07:00发布

问题:

Which .htaccess redirect rule(s) would one use to create all of the following forwards?

  • http://old.io --> http://new.com?pa=va
  • http://old.io/ --> http://new.com/?pa=va
  • http://old.io/abc --> http://new.com/abc?pa=va
  • http://old.io#def --> http://new.com#def?pa=va
  • http://old.io/abc#def --> http://new.com/abc#def?pa=va

. . . and include any other arbitrary parameters:

  • http://old.io?p2=v2 --> http://new.com?pa=va&p2=v2
  • http://old.io/?p2=v2 --> http://new.com/?pa=va&p2=v2
  • http://old.io/abc?p2=v2 --> http://new.com/abc?pa=va&p2=v2
  • http://old.io#def?p2=v2 --> http://new.com#def?pa=va&p2=v2
  • http://old.io/abc#def?p2=v2 --> http://new.com/abc#def?pa=va&p2=v2

回答1:

So, basically you need to add a pa=va to the query string of any possible constructed URL:

RewriteEngine on
RewriteBase /

# Check if the host matches old.io,
# You might want to add www\. to that.
RewriteCond %{HTTP_HOST} ^old\.io

# Rewrite URLs with empty querystring
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)$ http://new.com/$1?pa=va [L,R]

# Rewrite URLs with non-empty querystring    
RewriteCond %{QUERY_STRING} ^.+$
RewriteRule ^(.*)$ http://new.com/$1?pa=va&%{QUERY_STRING} [L,R]

Note that the anchor hash part needs to come after the query string.

You can test it online, if you wish.