LoginSignup
7
3

More than 3 years have passed since last update.

nginxのバーチャルサーバ (バーチャルホスト) の設定を理解するまでのメモ

Last updated at Posted at 2020-12-10

はじめに

debianに入れたnginxを元にしてのメモになります。

各ディレクティブの設定は、こちらで確認できます。
nginx ドキュメント 日本語訳

nginxの全体構成

nginxはモジュールの集合体です。
一つ一つのモジュールは、ディレクティブというコンパイル時に使用される補足情報がセットになっています。

ディレクティブには、シンプルディレクティブと、ブロックディレクティブがあります。

# シンプルディレクティブ
# [要素] [要素];
# 例
user www-data;

# ブロックディレクティブ
# 要素 { シンプルディレクティブ... }
# 例
events {
        worker_connections 768;
}

ブロックディレクティブが他のディレクティブを持つことができる場合は、コンテキストと呼ばれます。

コンテキストには主に

  • evnets
  • http
  • server
  • location

があります。継承構造はディレクティブによって予め決められており、それを守らないとエラーが起きます。

各モジュール、ディレクティブの詳しい定義は以下を参照してください。
ngx_http_core_module モジュール 日本語訳

Nginxのファイル読み込み順序

nginxではnginx.confという設定ファイルが最初に読み込まれます。

私の手元のDebianだと
/etc/nginx/nginx.confに設置されています。

Nginx/DirectoryStructure - Debian Wiki

このファイルはNginxパッケージメンテナによって管理されており基本は編集しないで進めます。
中身は以下のように定義されています。

/etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}


#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
# 
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

今回はバーチャルサーバの設定がしたいので

/etc/nginx/nginx.conf
        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

に記載されている/etc/nginx/sites-enabled/のファイルを編集していきます。

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/run/php/php7.3-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}

ファイル中に以下の記載があります。

You can move that to a different file under sites-available/ and symlink that to sites-enabled/ to enable it.

なので、以下のような手順で設定を書いていきます。

  • sites-availableにドメイン別のファイルを作成し各々のファイルに設定を記述
  • sites-enabledはsites-availableのシンボリックリンクを張る

sites-availableに複数のファイルを用意しておき、必要に応じて、シンボリックリンクの切り替えをすることで、設定の自由度を高められる仕様になっているようです。

公式のドキュメントに記述を探しましたが、nginxのディレクトリ構造がOSごとに異なるので、

今回は、ファイルの読み込まれる順番に仕様を解釈していきました。

実際の概要把握の方法としては、

find / -type d -name nginx | xargs grep -r http

のようにコマンドで、httpが設定されているところの一覧を出して、ざっくりと設定されている場所を探し出すという方法がなれてくるとできるようです。

メモ

サーバのディレクトリ構造がOS依存ということを理解していなかったため、公式のドキュメントを呼んで、混乱していましたが、まずはinstallしたnginx自体をgrep等で当たりをつけながら探索して、デフォルトの設定ファイルから仕様を読み解いていくのが早かったです。

参考

Nginx/DirectoryStructure - Debian Wiki
ビギナーのガイド 日本語訳
nginx documentation
nginxでsites-availableとsites-enabledを用いたバーチャルホストの設定 - Memento
Nginxのバーチャルサーバ設定 - Qiita

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3