子持ちプログラマーの日記

子持ちのプログラマーがWeb関連の技術、育児、ガンプラのことを書くブログ

【nginx】バーチャルホストの設定

nginxのバーチャルホストを設定を試したいと思います。

前提

2つのサイトを運用すると想定。
それぞれドキュメントルート以下にindex.htmlを置き、ドメイン名を書いておく。
ドメインなどは以下のようにする

サイト1

  • ドメイン
    • example1.com
  • ドキュメントルート
    • /etc/nginx/conf.d/example1.com/

サイト2

  • ドメイン
    • example2.com
  • ドキュメントルート
    • /etc/nginx/conf.d/example2.com/

設定

ドメイン名.confを作り、ドメインごとに設定ファイルを分けるようにした。

example1.com用の設定

# vi /etc/nginx/conf.d/example1.com.conf

server {
	listen 80;
	server_name example1.com;
	access_log  /var/log/nginx/example1.com.access.log;
	location / {
		root   /usr/share/nginx/example1.com;
		index  index.html;
	}
}

example2.com用の設定

# vi /etc/nginx/conf.d/example2.com.conf

server {
	listen 80;
	server_name example2.com;
	access_log  /var/log/nginx/example2.com.access.log;
	location / {
		root   /usr/share/nginx/example2.com;
		index  index.html;
	}
}

設定を反映

設定ファイルができたらnginxを再起動して、設定を反映する必要があります。

設定が間違っていたりして起動出来なくなるのはよろしくないので、
設定が問題ないか確認。

# /etc/init.d/nginx configtest
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

上記のように「test is successful」となればOKなので再起動します。

# /etc/init.d/nginx reload
nginx を再読み込み中:                                      [  OK  ]

確認

ブラウザで、「http://example1.com」、「http://example2.com」にアクセスして、
以下のようにそれぞれのドメイン名が表示されればOKです。

http://example1.com
f:id:kouji0607:20150502012245p:plain

http://example2.com
f:id:kouji0607:20150502012254p:plain