nginxの設定
カテゴリ:Webサーバ
CentOS/Ubuntu 両対応
nginxの基本的な設定について解説いたします。
nginxの設定ファイル
nginxの設定ファイルは /etc/nginx/nginx.conf です。
設定ファイルは{}で囲まれたブロック単位で記述します。
初期設定時のnginx.confファイル:
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
設定ファイルの内容を見て想像できるようにhttpブロックがhttpサーバーの設定です。
ブロックは入れ子構造で設定するため、HTTPサーバーを追加する場合、httpブロック内に、serverブロックを追加し必要なパラメーターを記述します。
serverブロックの追加
serverブロックで最低限必要なパラメーターは以下になるかと思います。
| パラメーター | 説明 |
|---|---|
| listen | リスンするIPアドレスとポートを指定(ポートのみを指定した場合すてべてIPアドレスにバインド) |
| server_name | サーバ名を指定 |
| location | ドキュメントルートからの相対パスを指定 |
| root | ドキュメントルートのパスを指定(デフォルト/usr/share/nginx/html) |
| index | ファイル名が指定されていない場合に自動で探して表示させたいファイルを指定 |
| charset | レスポンスヘッダのContent-typeを指定する |
serverブロックの設定例)
http {
server {
listen 80;
server_name example.com;
location / {
root /var/www/html
index index.html index.htm;
}
charset UTF-8;
}
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
設定後、以下のコマンドを実行し、nginxを起動します。
# systemtl restart nginx
nginxが80番ポートでリスンしていることを確認します。
# ss -anp | grep :80
tcp LISTEN 0 128 *:80 *:* users:(("nginx",pid=29857,fd=6),("nginx",pid=29856,fd=6))
テストページの表示
/var/www/html/index.htmlファイルを作成し、簡単なHTMLページを記述します。
nginxを再起動した上でWebブラウザから http://サーバーのIP/ を開き、テストページが表示されることを確認します。
仮想ホストの設定
仮想ホストを設定する場合は、以下のようにhttpブロック内にserverブロックを追加します。
server_nameにサーバ名、rootにドキュメントルートを指定する以外は同じです。
server {
listen 80;
server_name hoge1.com;
location / {
root /var/www/html/hoge1
index index.html index.htm;
}
charset UTF-8;
}
server {
listen 80;
server_name hoge2.com;
location / {
root /var/www/html/hoge2
index index.html index.htm;
}
charset UTF-8;
}
参考サイト:
https://docs.nginx.com/nginx/admin-guide/web-server/web-server/
公開日時:2019年05月05日 22:10:21
最終更新日時:2021年08月19日 12:56:19



