Rewrite subdomain

2019-06-01 02:26发布

问题:

Obviously a pretty simple question: how do I rewrite

(value1).example.com/(value2)

to

/(value1)/(value2)

I've tried a couple of things without success.

Thank you in advance.

回答1:

Try this rule:

RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$
RewriteCond $1/%1 !^([^/]+)/\1$
RewriteRule ^/([^/]+)? /%1%{REQUEST_URI} [L]

Some explanation: My previous suggestion caused an infinite recursion as the L flag causes a restart of the rewriting process with the new URL:

Remember, however, that if the RewriteRule generates an internal redirect (which frequently occurs when rewriting in a per-directory context), this will reinject the request and will cause processing to be repeated starting from the first RewriteRule.

The second condition will avoid this as it compares the subdomain part with the first path segment. And only if they are different the condition is true and the rewrite takes place.