Reuse subdomain in a rewrite rule

2019-09-07 16:08发布

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

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-07 16:24

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.

查看更多
\"骚年 ilove
3楼-- · 2019-09-07 16:37

Try rewrite condition backreferences:

RewriteCond %{HTTP_HOST} ([^\.]+).example.com [NC]
RewriteRule ^.*$ http://example.com/private/%1/public/si.php [L]
查看更多
登录 后发表回答