问题
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
回答1:
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.
回答2:
Try rewrite condition backreferences:
RewriteCond %{HTTP_HOST} ([^\.]+).example.com [NC]
RewriteRule ^.*$ http://example.com/private/%1/public/si.php [L]
来源:https://stackoverflow.com/questions/14062575/reuse-subdomain-in-a-rewrite-rule