CentOS7.9にnginxをインストールする方法
環境
VPS環境を想定して記載する。
各種環境は以下とするので、読み替えて下さい。
IP:999.99.99.999
ドメイン:example.com
サーバー環境準備
サーバーにSSH接続
ssh root@999.99.99.999
必要なパッケージのインストール
yum install yum-utils
yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
nginxの環境構築
nginxのインストール
nginxのインストール用の定義を記載するために、以下のコマンドを実行する。
vi /etc/yum.repos.d/nginx.repo
「/etc/yum.repos.d/nginx.repo」の内容は以下を記載する。
[nginx]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
以下のコマンドでnginxのインストールを実行する。
yum-config-manager --enable nginx
yum install nginx
nginxの起動、自動起動設定
以下のコマンドでnginxの起動と、サーバー再起動後の自動起動の設定を行う。
systemctl start nginx
systemctl enable nginx
nginxのバージョン非表示
nginx のバージョンを表示にするための設定を行うために以下のコマンドを実行します。
vi /etc/nginx/nginx.conf
ファイル内に、以下の記述を追加します。
(用意されている「http」の中括弧の中に「server_tokens off;」を追加します。)
http {
~~~~~省略~~~~~
server_tokens off;
~~~~~省略~~~~~
}
nginxを再起動して上記の設定を反映させます。
systemctl restart nginx
ファイアーウォールの設定
以下のコマンドを実行して、「http」「https」のポートを解放します。
firewall-cmd --add-service=http --zone=public --permanent
firewall-cmd --add-service=https --zone=public --permanent
firewall-cmd --reload
Let's EncryptのSSL証明書の設定
必要なパッケージのインストールを行います。
yum install certbot python2-certbot-nginx
以下で証明書の発行を行います。
certbot --nginx certonly -d example.com
nginxのHTTPSリダイレクト設定
以下のコマンドでドメインの設定ファイルを修正します。
vi /etc/nginx/conf.d/example.com.conf
以下の内容を記載します。
※Apatchと同じディレクトリ(/var/www/html)をルートにしていますが、各自で任意のディレクトリに変更して下さい。
server {
listen 443 ssl;
server_name example.com;
root /var/www/html;
index index.html;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_prefer_server_ciphers on;
}
server {
listen 80;
server_name example.com;
return 301 [https://$host$request_uri;](https://$host$request_uri;)
}
nginxの再起動を実施します。
systemctl restart nginx