Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Let's say I have x.com and y.com. On z.com, I have a directory called x.com/ and another called y.com/. I have a CNAME record mapping x.com and y.com to z.com.

What I want to achieve is this;

A file is accessed on one of the end domains;
x.com/test.txt

This should then map to;
z.com/x.com/test.txt

The way I thought of going about this is:

RewriteCond %{REQUEST_URI} !^https:\/\/z\.com\/switch.php\?.+ [NC]
RewriteRule ^(.*) https://z.com/switch.php?f=$1 [R=301,NE,L]

I would then use switch.php to echo $_SERVER['HTTP_HOST']/file.txt where the filepath is specified in $_GET['f'], placed there by .htaccess.

Not only does the .htaccess cause an infinite loop, but I believe it's possible to do this just in .htaccess without switch.php at all. The loop is because the regex isn't working to exclude the file being rewritten to. I'd imagine this is because the $1 has no capture group in the regex, but I have no idea how to create a capture group while having a negated regex. I'd need to say 'if it's not switch.php?anything, set $1 to whatever's after the hostname'.

Adding this rule stops the infinite loop but no rewriting happens:

RewriteCond %{REQUEST_URI} ^https:\/\/z\.com\/(.+) [NC]

If you could help me to fix this I'd really appreciate it.

What I have tried:

Everything mentioned in question, plus a lot of googling
Posted
Updated 19-Apr-18 2:31am
v4

1 solution

You are checking the wrong variable REQUEST_URI. That does not contain the scheme (HTTP, HTTPS) and the host name:
REQUEST_URI
The path component of the requested URI, such as "/index.html". This notably excludes the query string which is available as its own variable named QUERY_STRING.
You have to use HTTP_HOST instead.

I have not used mod_rewrite much but it should be simple by checking if the host is x.com and if so redirect to the x.com sub directory on z.com:
RewriteCond %{HTTP_HOST} ^x\.com$
RewriteRule "^(.+)" "/x.com$1"
and similar for y.com.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900