可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Hi guys I'm setting up mywebapplication to give unique urls for users such as uniquename.mysite.com, anotheuniqname.mysite.com etc.
I want to be able to in a php script grab the subdomain part of the url. Would be nice if I can get it as a GET variable - I think it can be done with htaccess. Any ideas?
回答1:
$subdomain = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], '.'));
To make sure there's a valid subdomain:
$urlExplode = explode('.', $_SERVER['HTTP_HOST']);
if (count($urlExplode) > 2 && $urlExplode[0] !== 'www') {
$subdomain = $urlExplode[0];
}
else {
// treat as www.mysite.com or mysite.com
}
回答2:
I would try this (at the beginning of your PHP code):
$_GET['subdomain'] = substr($_SERVER['SERVER_NAME'], 0, strrpos($_SERVER['SERVER_NAME'], '.'));
Explanation: strrpos
find the last occurance of '.' in the accessed domain, substr
then returns the string up to this position. I assigned the return value to a $_GET
var so you can use it as if it were a normal URL-parameter.
回答3:
Put this in your bootstrap file:
$tmp = explode(".", $_SERVER["HTTP_HOST"], 2);
$_GET["subdomain"] = $tmp[0];
回答4:
Ali - don't you mean a $_SERVER
variable as $_GET
would be related to the querystring ??
if so, then you could try:
$_SERVER['HTTP_HOST']
jim
[edit] - see http://roshanbh.com.np/2008/05/useful-server-variables-php.html for a few examples that may help
回答5:
Do you want something along the lines of:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^[a-z0-9-]+\.yoursite\.com$
RewriteRule !^index\.php$ index.php [L]
you could then get the subdomain using
<?php
preg_match('/^http:\/\/([a-z0-9-]+)\.yoursite.com$', $_SERVER['HTTP_HOST'], $matches);
$_GET['username'] = $matches[1];
?>
回答6:
If you really want to use mod_rewrite
in your .htaccess
file, you could do something like this (assuming your script is index.php
in this example):
RewriteEngine On
# Prevent people from going to to index.php directly and spoofing the
# subdomain value, since this may not be a desirable action
RewriteCond %{THE_REQUEST} ^[A-Z]+\sindex\.php.*(\?|&)subdomain=
RewriteRule ^.*$ http://%{HTTP_HOST}/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} !^www
RewriteCond %{HTTP_HOST} ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^.*$ index.php?subdomain=%1
回答7:
This little function will simply get your " www.website.com
" or in your case " subdomain.website.com
", and then split it up in 3 parts ( 0=>"www", 1=>"website", 2=>"com" )
, and then return value 1
, which is either " www
" or your subdomain name.
function isSubdomain()
{
$host = $_SERVER['HTTP_HOST'];
$host = explode('.',$host);
$host = (is_array($host)?$host[0]:$host);
return $host;
}
Exaple: If your website is " admin.website.com
", you will receive "admin
".