How to redirect from all subdomains to a php file with .htaccess?

Member

by mike , in category: SEO , a year ago

How to redirect from all subdomains to a php file with .htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by domenico.weimann , a year ago

@mike 

To redirect all subdomains to a PHP file using .htaccess, you can use the following code:

1
2
3
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+).yourdomain.com$ [NC]
RewriteRule ^(.*)$ http://yourdomain.com/your-php-file.php?subdomain=%1 [L,R=301]


This is assuming you want to redirect all subdomains to the same PHP file, and you want the subdomain name to be passed as a parameter (subdomain) to the PHP file.


Explanation of the code:

  1. RewriteEngine On - Enables the Apache rewrite engine.
  2. RewriteCond %{HTTP_HOST} ^(.+).yourdomain.com$ [NC] - Matches the subdomain part of the URL. It uses a regular expression to capture the subdomain part.
  3. RewriteRule ^(.*)$ http://yourdomain.com/your-php-file.php?subdomain=%1 [L,R=301] - Redirects the request to the PHP file, passing the captured subdomain as a parameter. The [L,R=301] part tells Apache to apply this rule and issue a permanent redirect.


Make sure to replace yourdomain.com with your actual domain name and your-php-file.php with the filename of your PHP file that you want to redirect to.