勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

ブログサービスの様にサブドメインを動的に生成する方法  

   2024/04/18  PHP サーバー

ブログサービスの様に「hoge」というログインIDを作成した際「hoge.blog.jp」のようにサブドメインを自動的に生成したい。また同時にサーバ側では「hoge」というディレクトリを作成し、当該ドメインにアクセスした場合はそのディレクトリを参照させたい。以下に対応方法のメモ。

 

DNSの設定

まずはDNS側の設定をする。「○○.blog.jp」の○○がどのような値でも「111.222.333.444」というIPに向けたい場合、ワイルドカードが使えるらしい。下記がワイルドカードの例。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
RECORD NAME *(ワイルドカード)
TYPE A
TTL 7200(無料プランだと固定)
Priority 空白でOK
Content 111.222.333.444(サーバーのIP入れる)
RECORD NAME *(ワイルドカード) TYPE A TTL 7200(無料プランだと固定) Priority 空白でOK Content 111.222.333.444(サーバーのIP入れる)
RECORD NAME *(ワイルドカード)
TYPE A
TTL 7200(無料プランだと固定)
Priority 空白でOK
Content 111.222.333.444(サーバーのIP入れる)

 

あと、ネームサーバーも変えないといけない。今回はtkドメインで試したんだけど、Management Toolsの中にNameserversというのがあるので、Use custom nameserversの中に以下を入れておく。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ns1.dzndns.com
ns2.dzndns.com
ns3.dzndns.com
ns4.dzndns.com
ns1.dzndns.com ns2.dzndns.com ns3.dzndns.com ns4.dzndns.com
ns1.dzndns.com
ns2.dzndns.com
ns3.dzndns.com
ns4.dzndns.com

これで「○○.blog.jp」とした場合に○○に何を入れても「111.222.333.444」に飛ぶようになる。

 

apacheの設定

次にapache側の設定。httpd.confに以下を記述する。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#↓↓コメントアウト付いている場合は外す
NameVirtualHost *:80
#↓↓下記を追記
<VirtualHost *:80>
ServerAdmin blog.jp
ServerName blog.jp
ServerAlias *.blog.jp
VirtualDocumentRoot /var/www/html/%1
ErrorLog logs/error_log
CustomLog logs/access_log common
</VirtualHost>
#↓↓コメントアウト付いている場合は外す NameVirtualHost *:80 #↓↓下記を追記 <VirtualHost *:80> ServerAdmin blog.jp ServerName blog.jp ServerAlias *.blog.jp VirtualDocumentRoot /var/www/html/%1 ErrorLog logs/error_log CustomLog logs/access_log common </VirtualHost>
#↓↓コメントアウト付いている場合は外す
NameVirtualHost *:80

#↓↓下記を追記
<VirtualHost *:80>
ServerAdmin blog.jp
ServerName blog.jp
ServerAlias *.blog.jp
VirtualDocumentRoot /var/www/html/%1
ErrorLog logs/error_log
CustomLog logs/access_log common
</VirtualHost>

こうすることで「hoge.blog.jp」というURLを叩いた場合「/var/www/html/hoge」がドキュメントルートとなる。

 

PHPでディレクトリ生成

あとはアカウント作成フォームとかと組み合わせて以下のような形でディレクトリをPHP側から作成することで、ユーザーのIDがサブドメインとして使えるようになる。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$dirName = 'hoge';
$dirPath = '/var/www/html/' . $dirName;
mkdir($dirPath, 0755);
$dirName = 'hoge'; $dirPath = '/var/www/html/' . $dirName; mkdir($dirPath, 0755);
$dirName = 'hoge';
$dirPath = '/var/www/html/' . $dirName;
mkdir($dirPath, 0755);

 - PHP サーバー

  関連記事

VPSに無料SSLのLet's Encryptを導入

SSLといえば有料という認識だったが、無料のものも出てきているという話を聞いた。 ...

中国のIPアドレスをiptablesで拒否、遮断する

レンタルしているVPSの一つが最近よく落ちる。原因はどうも海外、特に中国から不正 ...

SSHのセキュリティ設定(暗号方式関連)について

SSHのセキュリティ設定をする事があった。設定内容は指示を貰えたので作業自体は問 ...

CentOS6.10に無料SSL(Let's Encrypt)を導入

以前にもVPSにLet's Encryptを導入するという記事を書いたが、テスト ...

OpenLiteSpeedにvsftpdを導入しFTPクライアントソフトから接続する方法

先日Almalinux8系に1-Click InstallでOpenLiteSp ...

S