How to write a htaccess file to wildcard folder to

2019-08-12 18:31发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-08-12 19:21

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+).

查看更多
登录 后发表回答