0

I'm a bit stuck with my redirect rule. Little example better than a long speech, here goes the Great Ugliness:

IndexIgnore *
ErrorDocument 404 http://www.example.com
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.  [NC]
RewriteRule ^([^\.]+)\.example\.com$ http://example.com/private/$1/public/si.php  [L]

My objective is to get the subdomain ([^\.]+) and use it in the redirection instead of $1. For example, test.example.com should redirect to http://example.com/private/test/public/si.php

Thank you for any help.

Regards, S.

final working htaccess:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.  [NC]
RewriteCond %{REQUEST_URI} !^/private/
RewriteCond %{HTTP_HOST} ([^\.]+).example.com [NC]
RewriteRule ^ /private/%1/public/$1  [R=301,L]

redirects anysub.example.com/anypage to anysub.example.com/private/anysub/public/anypage

Sebas
  • 21,192
  • 9
  • 55
  • 109

2 Answers2

2

The string used to match against the pattern of a RewriteRule will never contain the hostname, only the URI and without any query string. If you are to ignore what the actual URI is, then you don't need a pattern in the RewriteRule to match anything. You'd need to use a % symbol to backreference a previous grouping in a RewriteCond

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule ^ http://example.com/private/%1/public/si.php [L]

You can add a R=301 flag in the rule's square brackets to make the redirect permanent.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • if the way to filter is to use RewriteCond, I don't get what is the use of the pattern of rewriterule. Could you explain it to me? Also, it is working yet I wish the url displayed by the browser were the short one i.e. test.example.com; it appears translated so it shows the full one. – Sebas Dec 28 '12 at 02:26
  • @Sebas The `^` character just means "the beginning of the URI", it's really no different than `.*`. Essentially it matches everything. If you don't want to redirect the browser (redirects **always** change what's in the browser's URL address bar) then remove the `http://example.com` from the rule's target. – Jon Lin Dec 28 '12 at 02:29
  • perfect, i had to add a filter to avoid recursive redirections and voilá! thanks for your help – Sebas Dec 28 '12 at 02:33
1

Try rewrite condition backreferences:

RewriteCond %{HTTP_HOST} ([^\.]+).example.com [NC]
RewriteRule ^.*$ http://example.com/private/%1/public/si.php [L]
  • thank you, this is working. The answer of Jon is slightly more elaborated that's why I'll however accepted his post. Thanks again and welcome to StackOverflow – Sebas Dec 28 '12 at 02:24