development

.htaccess (PHP)를 사용하여 즉시 하위 도메인 만들기

big-blog 2020. 7. 12. 08:56
반응형

.htaccess (PHP)를 사용하여 즉시 하위 도메인 만들기


가입 할 때 사용자 계정 영역의 웹 사이트에 하위 도메인을 만드는 시스템을 만들고 싶습니다.

예 : johndoe.website.com

.htaccess 파일과 관련이 있고 웹 사이트의 다른 위치로 리디렉션 될 수 있다고 생각합니까? 나는 실제로 모른다. 그러나 나를 시작하는 모든 정보는 크게 감사하겠습니다.

가입 영역을 만드는 것은 문제가되지 않습니다.이 작업은 여러 번 수행했습니다. 하위 도메인으로 시작할 위치가 확실하지 않습니다.


빠른 런 다운

  1. DNS 서버 * .website.com에 와일드 카드 도메인을 만들어야합니다.
  2. 그런 다음 호스트 컨테이너에서 와일드 카드 * .website.com도 지정해야합니다. 이는 DOC 에서 수행됩니다.ServerAlias
  3. 그런 다음 PHP에서 하위 도메인을 추출하여 확인하고 적절한 데이터를 표시하십시오.

긴 버전

1. 와일드 카드 DNS 항목 만들기

DNS 설정에서 와 같은 와일드 카드 도메인 항목 을 만들어야합니다 *.example.org. 와일드 카드 항목은 다음과 같습니다.

*.example.org.   3600  A  127.0.0.1

2. 호스트에 와일드 카드 포함

다음으로 Apache 구성에서 ServerAlias DOCs 지시문에 와일드 카드를 지정하는 가상 호스트 컨테이너를 설정해야합니다 . 가상 호스트 컨테이너의 예 :

<VirtualHost *:80>
  ServerName server.example.org
  ServerAlias *.example.org
  UseCanonicalName Off
</VirtualHost>

3. PHP에서 어떤 서브 도메인을 만드십시오.

그런 다음 PHP 스크립트에서 $_SERVERsuper 전역 변수를 확인 하여 도메인을 찾을 수 있습니다 . 다음은 PHP에서 하위 도메인을 가져 오는 예입니다.

preg_match('/([^.]+)\.example\.org/', $_SERVER['SERVER_NAME'], $matches);
if(isset($matches[1])) {
    $subdomain = $matches[1];
}

www.subdomain.example.org 또는 subdomain.example.org를 통해 사이트를 방문하는 사람들을 위해 정규식을 사용했습니다.

www를 다루지 않아도 될 경우. (또는 다른 하위 도메인) 다음과 같이 단순히 하위 문자열을 사용할 수 있습니다.

$subdomain = substr(
                 $_SERVER['SERVER_NAME'], 0,
                 strpos($_SERVER['SERVER_NAME'], '.')
             );

대규모 가상 호스팅

대량 가상 호스팅은 질문과 같이 응용 프로그램을 강력하게 사용하려고 시도하지 않고 많은 다른 웹 사이트를 호스팅하는 데 일반적으로 사용한다는 점에서 위와 약간 다릅니다.

내 블로그게시물에서 mod_rewrite 기반 대량 가상 호스팅 환경을 문서화 했습니다.이 경로를 원하는 경로인지 확인할 수 있습니다. 물론 각각의 Apache 매뉴얼 페이지도 있습니다.

Apache는 또한 내가 사용한 mod_rewrite 메소드보다 약간 덜 유연한 대량 가상 호스팅을 처리하는 내부 방법을 가지고 있습니다. 이것은 모두 Apache Dynamically Configured Mass Virtual Hosting 매뉴얼 페이지에 설명되어 있습니다.


모든 하위 도메인을 처음에 허용 한 다음 하위 도메인이 유효한지 확인할 수 있습니다. 예를 들면 다음과 같습니다.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$
RewriteRule !^index\.php$ index.php [L]

내부에서 index.php다음을 사용하여 하위 도메인을 추출 할 수 있습니다.

if (preg_match('/^([^.]+)\.example\.com$/', $_SERVER['HTTP_HOST'], $match)) {
    var_dump($match[1]);
}

그러나이 모든 것은 웹 서버가 모든 하위 도메인 이름을 허용해야합니다.


DNS 와일드 카드를 설정하는 것 외에도 Apache위한 Dynamic Mass Virtual Hosting을 살펴보고 싶었습니다.


가장 쉬운 방법은 모든 하위 도메인 (와일드 카드 * 사용)을 / wwwroot를 가리 키도록 리디렉션하는 것입니다. 그런 다음 다음 코드를 사용하여 .htaccess를이 폴더에 넣으십시오.

RewriteCond %{ENV:REDIRECT_SUBDOMAIN} ="" 
RewriteCond %{HTTP_HOST} ^([a-z0-9][-a-z0-9]+)\.domain\.com\.?(:80)?$ [NC] 
RewriteCond %{DOCUMENT_ROOT}/%1 -d 
RewriteRule ^(.*) %1/$1 [E=SUBDOMAIN:%1,L] 
RewriteRule ^ - [E=SUBDOMAIN:%{ENV:REDIRECT_SUBDOMAIN},L]

이렇게하면 / wwwroot 폴더의 모든 하위 폴더가 하위 도메인 (foldername.domain.com)을 통해 허용됩니다.

몇 년 전에 http://www.webmasterworld.com/apache/3163397.htm 에서 발견되었습니다 .


I found it easier doing it with PHP. In fact is creating a subdomain within cPanel and create your folder under the desired domain name. As you will do it manually in cPanel but all it's done in milliseconds by a simple PHP function. No click necessary :)

function create_subdomain($subDomain,$cPanelUser,$cPanelPass,$rootDomain) {

    //  $buildRequest = "/frontend/x3/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain;

    $buildRequest = "/frontend/x3/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain . "&dir=public_html/subdomains/" . $subDomain;

    $openSocket = fsockopen('localhost',2082);
    if(!$openSocket) {
        return "Socket error";
        exit();
    }

    $authString = $cPanelUser . ":" . $cPanelPass;
    $authPass = base64_encode($authString);
    $buildHeaders  = "GET " . $buildRequest ."\r\n";
    $buildHeaders .= "HTTP/1.0\r\n";
    $buildHeaders .= "Host:localhost\r\n";
    $buildHeaders .= "Authorization: Basic " . $authPass . "\r\n";
    $buildHeaders .= "\r\n";

    fputs($openSocket, $buildHeaders);
        while(!feof($openSocket)) {
           fgets($openSocket,128);
        }
    fclose($openSocket);

    $newDomain = "http://" . $subDomain . "." . $rootDomain . "/";

   //  return "Created subdomain $newDomain";

}

It's nothing to do with .htaccess. You'll need to set up DNS records and virtual hosting for the subdomains.


Mod_vhost_alias is the right module to do this.

With one line you can tell Apache to look at the right place, with directory hashing, etc. For example, the line:

VirtualDocumentRoot /http/users/%3.1/%3.2/%3

would tell Apache to set the document root to /http/users/s/u/subdomain when requested for subdomain.yourdomain.com


I think the wild card DNS with Apache's Dynamic Mass Virtual Hosting is a reasonable solution also. Although, I have never tried it.

If you have the need to scale out to multiple servers or the other solutions just don't work for you, I recommend using a database driven DNS server. I have successfully used MyDNS in the past. Since it uses MySQL (or PostgreSQL) you can update your DNS on the fly with PHP or just about anything else. The code doesn't look like it has been updated in a while, but it's DNS and therefore not exactly cutting edge.


Wildcard subdomain creation methods

FIrst you have to create the DNS settings using your server DNS editor.

  1. Create A record in DNS settings with host * wild card in server ip address.

    * 1400 IN A ip_address

  2. Create once again a A record in DNS settings with host @ or domain_name.tld in server ip address. tld means top level domains or the extension of the domains such as .com, .org, etc....

    @ 1400 IN A ip_address or domain_name.tld 1400 IN A ip_address

  3. Create CNAME record like:

    www 1400 IN A domainname.tld

  4. Create the subdomain with * wildcard like *.domain.tld
  5. Create htaccess in your subdomain directory of *.domain.tld and put this code :

    Options +FollowSymLinks 
    RewriteEngine On 
    RewriteBase /
    RewriteRule ^([aA-zZ0-9]+)$ index.php?data=$1
    RewriteCond %{HTTP_HOST} ^([aA-zZ0-9]+)\.([aA-zZ0-9-]+)\.([aA-zZ]+)
    RewriteRule ([aA-zZ0-9]+) index.php?data=%1
    

    Test your first wildcard subdomain like example.domainname.tld

If you are not interest to pass the data as parameter using the htaccess, you can also get the data by using the following coding:

define("SUBDOMAIN_PARENT","domainname.tld");   
class getData
    {
         function __construct()
        {
            $this->data="";
            $http_host=$_SERVER['HTTP_HOST'];
         $subdom_data= str_replace(SUBDOMAIN_PARENT,"",$http_host);
         $expl_subdom_data=explode(".",$subdom_data);
      $expl_subdom_data=array_filter($expl_subdom_data);

            if($expl_subdom_data!=NULL)
            {
           $this->data=end($expl_subdom_data);
            }
       }
    }
$GLOBALS['get_data']=new getData();

and use your global variable at any place like global $get_data.

echo $get_data->data; //example

(note: This class mainly used for get the exact subdomainname from http_host. because some extra names combined before your subdomain is also applicable like www.example.domainname.tld. This return $_GET['data']='wwww' So my suggestion is to use the $_SERVER['http_host'] for get the exact values instead of using the $_SERVER['query_string'] or passed htaccess parameters in your index page)

6.Speed up the execution of this wildcard subdomains use N seconds in TTL - DNS SETTINGS.

7.Check the subdomain after your given ttl time (600 - 10 minutes) like => http://abc.domain.tld

(note: wildcard subdomains not override the existed subdomains. Because First priority always for your existed subdomains)

참고URL : https://stackoverflow.com/questions/586129/create-subdomains-on-the-fly-with-htaccess-php

반응형