.htaccess rewrite subdomain to directory and keep subdomain in url

断了今生、忘了曾经 提交于 2019-12-18 12:33:09

问题


I need to rewrite a subdomain to a subdirectory using .htaccess but keep the subdomain in the url like this:

Visited url in browser: sub1.domain.com

Served url: sub.domain.com/sub1/

I tried the following

RewriteCond %{HTTP_HOST} ^subdomain.domain.com
RewriteRule ^(.*)$ http://subdomain.domain.com/subdomain/$1 [L,NC,QSA]

but this leads to an endless loop. I know that it would be easier to do this by php but is there any solution for this with using .htaccess?


回答1:


You can use this rule in document root:

RewriteCond %{HTTP_HOST} ^subdomain\.domain\.com$ [NC]
RewriteRule ^((?!sub1/).*)$ /sub1/$1 [L,NC]

Explanation:

  • NC: Ignore case
  • L: Last rule
  • RewriteCond %{HTTP_HOST} line makes sure that rule only executes for subdomain
  • (?!sub1/) is negative lookahead expression that means of request is not starting with /sub1/
  • RewriteRule ^((?!sub1/).*)$ /sub1/$1 [L,NC] rewrites current path to /sub1/<uri>

References:

  • Apache mod_rewrite Introduction
  • Apache mod_rewrite Technical Details


来源:https://stackoverflow.com/questions/22394989/htaccess-rewrite-subdomain-to-directory-and-keep-subdomain-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!