Linodeでnginxを使用してubuntu20.04にワードプレスinstall

Linodeでnginxを使用してubuntu 22.04 | 20.04にワードプレス install

Linodeでnginxを使用してubuntu 22.04 | 20.04にワードプレス install

Nginxとは

Nginxは強力な負荷分散、リバースプロキシ、およびキャッシュ機能を備えたオープンソースのWebサーバーです。当初は、既存のWebサーバのスケーリングと同時実行の問題を解決するために設計されましたが そのイベントベースの非同期アーキテクチャにより、今日利用できるWebサーバの中で最も人気のある、最もパフォーマンスの高いWebサーバーの1つになっています。ですので安価なプラン提供すうるLinodeのなかからUbuntuを選び、それに載せるWordpressとの組み合わせは良い関係を補ってくれるでしょう。

構成上の留意

NGINX Webサーバーの使用が拡大するにつれて、NGINX、Incは、Apacheに既に慣れている人々の採用を容易にするために、過去に使用された構成や用語からNGINXを遠ざけるように取り組んできました。 Apacheに精通している場合は、複数のサイト構成(Apacheの用語では仮想ホストと呼ばれます)が/etc/apache/sites-available/に格納されていることをご存知でしょう。これは、/etc/apache/sites-enabled 内のファイルにシンボリックリンクします。ただし、NGINXの多くのガイドやブログ投稿では、これと同じ構成を推奨しています。ご想像のとおり、これにより混乱が生じ、NGINXが../sites-available/および../sites-enabled/ディレクトリとwww-dataユーザーを定期的に使用するという想定が生まれました。そうではありません。 確かにそれはできます。 DebianおよびUbuntuリポジトリのNGINXパッケージは、かなり前から構成をこれに変更しているため、構成ファイルが/sites-available に保存され、/sites-enabled にシンボリックリンクされているサイトを提供することは確かに機能するセットアップです。ただし、これは不要であり、DebianLinuxファミリだけがそれを必要とします。 Apache構成をNGINXに強制する必要はない、とNginxサイトは言っています。

Ubuntu20.04

まずはUbuntuのインストールですがLinodeではプランを選ぶのみとなっています。

Linodeサーバを構築していく前の基本事項

基本事項はこちらからご確認ください。

基本ソフトのインストール

Ubuntuのupdate

updateをインストールします。

$ sudo apt update

Nginxのインストール

Nginxをインストールします。

$ sudo apt-get install nginx

Nginxの起動

sudo systemctl stop nginx
sudo systemctl start nginx
sudo systemctl enable nginx

Nginxのログユーザを変える。

sudo chown -R www-data:www-data /var/log/nginx 
sudo find /var/log/nginx -type f -exec chmod 666 {} \; 
sudo find /var/log/nginx -type d -exec chmod 755 {} \;

PHPのインストール

以下のコマンドは、サードパーティのPPAをUbuntuに追加します。
※PHP8.1はこちらUbuntuでPHP8.1のインストール例
sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt install php7.4-fpm php7.4-common php7.4-mysql php7.4-gmp php7.4-curl php7.4-intl php7.4-mbstring php7.4-xmlrpc php7.4-gd php7.4-xml php7.4-cli php7.4-zip

PHP.ini編集

php.iniの編集をします。

sudo nano /etc/php/7.4/fpm/php.ini

下記であることを確認します。

※nano では Ctrl+Wで文字列検索

file_uploads = On
allow_url_fopen = On
short_open_tag = On
memory_limit = -1
cgi.fix_pathinfo = 0
upload_max_filesize = 100M
post_max_size = 30M
max_execution_time = 360
date.timezone = Japan/Tokyo 等

PHP-fpmリスタート

sudo systemctl restart php7.4-fpm

Nginxの実行ユーザの所有に変更

メインサイトの場合

※mysite.comを自サイトのドメインに置き換える

sudo chown -R www-data:www-data /var/www/html/mysite.com

ヴァーチャルサイトの場合

後ほどバーチャルブロックを作成した後に下記を実施

※mysite.comを自サイトのドメインに置き換える

sudo chown -R www-data:www-data /home/user/mysite.com/html

ユーザフォルダの権限を変える

sudo chmod o+x /home/user/

※Nginxバーチャルブロックの参考サイト

MySQLをUbuntuへインストール

sudo apt-get install mariadb-server mariadb-client

MySQLを起動

sudo systemctl is-enabled mariadb

MySQLのインストール

下記でMySQLのインストールを行います。

sudo mysql_secure_installation

インストールされてない場合は下記のように選択していくきます(例として)。

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB<br>SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current password for the root user. If you've just installed MariaDB, and haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none):<br>OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] n
... skipping.

You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!

By default, a MariaDB installation has an anonymous user, allowing anyone<br>to log into MariaDB without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
... Success!

Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
... Success!
By default, MariaDB comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.


Remove test database and access to it? [Y/n] y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!

Reloading the privilege tables will ensure that all changes made so far will take effect immediately.

Reload privilege tables now? [Y/n] y
... Success!

Cleaning up...

All done! If you've completed all of the above steps, your MariaDB installation should now be secure.

Thanks for using MariaDB!

MySQLへログイン(DB追加はここから)

サイト追加(DB追加)の場合はここから

sudo mysql -u root -p

DB作成

CREATE DATABASE データベース名;

ユーザ作成

CREATE USER 'ユーザ名'@'localhost' IDENTIFIED BY 'パスワード';

権限付与

GRANT ALL PRIVILEGES ON データベース名.* TO 'ユーザ名'@'localhost';
FLUSH PRIVILEGES;

サイトの追加(ヴァーチャルサーバブロックの設定)

バーチャルサイトディレクトリの作成

バーチャルサイト用のブロックをドメイン名example.comとして作成

sudo mkdir -p /home/ユーザ名/example.com/html 

バーチャルサイト用のファイルを/home/user/example.com/html ディレクトリに作成. indexファイルを作成し“Hello World” など表示してテストを行える。/home/user/example.com/index.html.

※ example.com をドメイン名と置き換える。

configurationファイルの作成

サーバ宣言ファイルの作成(実際には作成していないくても稼働している)

/etc/nginx/nginx.conf確認
/etc/nginx/conf.d/*.conf

サイトのConfigファイルを作成する。

/etc/nginx/sites-availableへ移動しdefaultからコピー

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/testsite.com

# Virtual Host configuration for example.com以上を削除して編集

コピーした.confファイルを編集

server {
    listen 80;
    listen [::]:80;
    root /var/www/wordpress;
    index  index.php index.html index.htm;
    server_name  example.com www.example.com;

    client_max_body_size 100M;
    autoindex off;
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
         include snippets/fastcgi-php.conf;
         fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
         include fastcgi_params;
    }
}

WordPress用のサイトconfigファイル(参考)

server {

        server_name xxxxxx.com www.xxxxxx.com;

        root /home/usr/xxxxxx.com/html;
        index index.html index.php;

        client_max_body_size 100M;
        autoindex off;

        set $cache_uri $request_uri;

    # POST requests and URLs with a query string should always go to PHP
    if ($request_method = POST) {
        set $cache_uri 'null cache';
    }
    if ($query_string != "") {
        set $cache_uri 'null cache';
    }
    # Don't cache URIs containing the following segments
    if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php
                          |wp-.*.php|/feed/|index.php|wp-comments-popup.php
                          |wp-links-opml.php|wp-locations.php |sitemap(_index)?.xml
                          |[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {

        set $cache_uri 'null cache';
    }

    # Don't use the cache for logged-in users or recent commenters
    if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+
                         |wp-postpass|wordpress_logged_in") {
        set $cache_uri 'null cache';
    }

# Use cached or actual file if it exists, otherwise pass request to WordPress
        location / {
#               try_files $uri $uri/ =404;
#                try_files $uri /index.php?$args;
        try_files /wp-content/cache/supercache/$http_host/$cache_uri/index.html
                  $uri $uri/ /index.php;
        }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        log_not_found off;
        access_log off;
    }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;

                include fastcgi_params;
        }

    # Cache static files for as long as possible
location ~*.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
        expires max;
        log_not_found off;
        access_log off;
    }





}

リンク作成

sudo ln -s /etc/nginx/sites-available/testsite.com.conf /etc/nginx/sites-enabled/testsite.com

ワードプレスファイルの取得

sudo cd /home/ユーザ名/example.com
sudo wget -c http://wordpress.org/latest.tar.gz

ワードプレスファイルの解凍

sudo tar -xzvf latest.tar.gz

ワードプレスファイルの移動

ホームディレクトリへ。

cd wordpress
sudo mv * ../html
*WordpressのGETの仕方

権限の確認

/etc/nginx/nginx.conf の1ライン目のユーザであること(のはず)

sudo chown -R nginxユーザ:nginxグループ html

Certbotを用いてLet’sEncrypte Clientのインストール

Installing the Certbot Let’s Encrypt Client

下記コマンドをでインストール

sudo apt-get install letsencrypt
sudo apt install certbot python3-certbot-nginx
sudo firewall-cmd --list-all
 

下記が出力されます。

public
   target: default
   icmp-block-inversion: no
   interfaces:
   sources:
   services: cockpit dhcpv6-client http ssh
   ports:
   protocols:
   masquerade: no
   forward-ports:
   source-ports:
   icmp-blocks:
   rich rules:
出ない場合はこちらでファイアウォールのインストール 
SSLチェッカーを利用するのも確認できます。

Obtaining a Certificate

これで、ドメインのSSL証明書をリクエストできます。 certbot Let’s Encryptクライアントを使用してNginxのSSL証明書を生成すると、クライアントは、パラメータとして提供されたドメインに有効な新しいSSL証明書を自動的に取得してインストールします。 複数のドメインまたはサブドメインに有効な単一の証明書をインストールする場合は、それらを追加のパラメーターとしてコマンドに渡すことができます。 パラメータのリストの最初のドメイン名は、Let’s Encryptが証明書を作成するために使用するベースドメインになります。そのため、リストの最初にトップレベルドメイン名を渡し、その後に追加のサブドメインまたはエイリアスを渡します。

sudo certbot --nginx -d your_domain -d www.your_domain

これにより、-nginxプラグインを使用してcertbotが実行され、ベースドメインはyour_domainになります。 対話型インストールを実行し、単一のドメインのみをカバーする証明書を取得するには、次のコマンドを使用してcertbotコマンドを実行します。

HTTP2の追加

/etc/nginx/sites-available/以下のファイルを変更します。

listenの箇所を変更するだけなのでとても簡単です。簡単のため、リダイレクト部分は省略します。

server { 
listen 443 ssl http2; 
server_name www.aexample.com;

Deffie-Hellman共有鍵長の延長

デフォルトのDeffie-Hellman鍵は長さが短く、セキュリティ上好ましくありません。独自に4096bitで生成しなおして、これを設定します。ホームディレクトリで作成して、設定ファイルと同じディレクトリに移します。ちなみに生成には結構時間がかかるので気長にお待ちを。

cd /etc/letsencrypt
openssl dhparam -out dhparam.pem 4096

完了後置き換えます。

sudo mv dhparam.pem ./ssl-dhparams.pem

バーチャルサーバブロック部分に追加。

# ssl_ciphers ECDHE+AESGCM:DHE+AESGCM:HIGH:!aNULL:!MD5;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
ssl_session_timeout 5m;
ssl_session_tickets off;ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
ssl_ecdh_curve secp384r1;
ssl_session_cache shared:SSL:1m;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";

certbotユーティリティは、証明書要求手順中にドメイン情報の入力を求めることもできます。 この機能を使用するには、ドメインなしでcertbotを呼び出します。

sudo certbot --nginx

sqlbind

yum install php-mysqlnd

参考

Linode(100USD付リファラルコード付き)

nginx

ubuntu

お買い物カゴ