How to write a htaccess file to wildcard folder to subdomain

半世苍凉 提交于 2020-01-05 07:42:26

问题


I'm trying to redirect all my folders (using a wildcard) to their subdomain. For example:

www.mywebsite.com/folder1 to folder1.mywebsite.com/
www.mywebsite.com/folder2 to folder2.mywebsite.com/
www.mywebsite.com/folder3 to folder3.mywebsite.com/

Now without writing a rule for each one of them, is there a way to redirect them all to their respective subdomain?

I tried:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.mywebsite\.com$
RewriteRule ^(.*)$ /%1/$1 [QSA]

But it gives me an internal error 500


回答1:


You need to keep the rules from looping, use a condition to first check if the /%1/$1 actually exists, or that the URI doesn't already start with %1

So:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.mywebsite\.com$
RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -d
RewriteRule ^(.*)$ /%1/$1 [QSA]

Or:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.mywebsite\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]

The !^/([^/]+)/([^:]*):\1 expression groups the first folder in the URI, and backreferences it with \1. If those are equal, then the first folder in the URI is %1 which is backreferenced to the previous match (\w+).



来源:https://stackoverflow.com/questions/13373006/how-to-write-a-htaccess-file-to-wildcard-folder-to-subdomain

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