简体   繁体   中英

How do I route all subdomains to index.php using htaccess without 301 redirect

I would like to set up an htaccess file that routes requests for any subdomain to the index.php file in the /public_html/ folder. I have already configured the DNS to accept wildcard subdomains.

I plan to give users a personalised url for the site and pass the username via the subdomain, so it is important that the url remains and hence 301 redirects are out of the question.

My htaccess currently looks like this, but does not work (server not found):

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.mydomain\.com$ [NC]
RewriteRule . /index.php?subdomain=%1 [L,QSA]

My end goal is to be able to get a url such as //joebloggs.mydomain.com/foo/bar to translate into something like //www.mydomain.com/index.php?user=joebloggs&route=/foo/bar .

What do I need to have in the htaccess file to make this work?

You can have it this way

# if request is for a subdomain (except "www")
RewriteCond %{HTTP_HOST} ^((?!www\.).+)\.mydomain\.com$ [NC]
# internally rewrite to index.php
RewriteRule ^((?!index\.php$).*)$ /index.php?subdomain=%1&route=$1 [L]

Since it seems the rule is executed when you're trying to navigate to the index.php, can't this be done with simple php logic within index.php?

I mightve misunderstood your goal, but it seems to me you could easily replace this with a GET. Your url would be ready for that approach, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM