Raspberry pi + Nginx + Nextcloudでクラウドサーバーを立ち上げる

#最初に
RaspberryPi + Nginx + Nextcloudについてまとめられている記事が少なかった為，自分が導入した手順をまとめました。 
導入にはかなりの時間がかかりましたが，おかげでNginx, phpまわりの勉強になったし，ストレージ容量も気にせずにクラウドサーバーを使えるようになったので良かったです。

#導入環境

###Raspberry Pi
Raspberry Pi3 Model B+ 2019

```
$ lsb_release -a
No LSB modules are available.
Distributor ID: Raspbian
Description:    Raspbian GNU/Linux 9.9 (stretch)
Release:        9.9
Codename:       stretch
```
###Nginx
```
$ nginx -V
nginx version: nginx/1.10.3
```

###php
```
$php -v
PHP 7.2.19-1+0~20190531112637.22+stretch~1.gbp75765b (cli) (built: May 31 2019 11:26:38) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
```
###Nextcloud
Nextcloud 16.0

#Nginxのインストール

```.bash
#nginxのインストール
$sudo apt update
$sudo apt install nginx -y

#nginxの起動
$systemctl start nginx
$systemctl enable nginx

```

#PHP-7.2-fpmのインストール
https://ayesh.me/Ubuntu-PHP-7.2
以下を順次実行

```.bash
$sudo apt install apt-transport-https lsb-release ca-certificates
$sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
$sudo sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'
$sudo apt update
$sudo apt upgrade
$sudo apt install mysql-server php7.2-xml php7.2-fpm php7.2-cli php7.2-cgi php7.2-mysql php7.2-mbstring php7.2-gd php7.2-curl php7.2-zip
```

#phpの設定

以下のファイルを下のように各行のコメントアウトをはずして修正

```.bash
$sudo nano /etc/php/7.2/fpm/pool.d/www.conf
```


```www.conf
listen = /var/run/php/php7.2-fpm.sock

listen.mode = 0666

env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp
```
同じ様に以下もコメントアウトをはずして修正。

```.bash
$sudo nano /etc/php/7.2/fpm/php-fpm.conf
```

```php-fpm.conf
daemonize = yes
```

#フリードメインの取得
[こちらのサイトを参考にしてください](http://kaimonodou.yuujuu.net/article/175583917.html)
お好きなドメイン名を取得し，以下の設定へ続きます。
(ここではexample.comというフリードメインを取得したとして続きます。）

#Let's Encrypt で Nginx にSSLを設定する
##Nginxの事前設定
Lets'Encryptをインストールする前に，先ほど取得したフリードメインを経由して外部からraspberry piにアクセスできるように設定します。

```.bash
$sudo nano /etc/nginx/sites-enabled/default
```
該当する行を以下のように修正

```
server_name example.com;

fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
```
```.bash
#設定を反映
$sudo nginx -t
$sudo nginx -s reload
```

外部から接続できるか確認します。
携帯電話などを使ってraspberry piとは別のネットワークから http://example.com にアクセスしNginxから何らかのレスポンスが返ってくれば完了です。


##Lets'Encryptのインストール
以下を実行

成功すれば　「Congratulations! ～」 に続く記述が表示される。

```.bash
$sudo apt -y install letsencrypt python3-certbot-nginx
$sudo certbot --nginx

...
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator webroot, Installer None
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): hogehoge@email.com

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: N
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for example.com
Using the webroot path /var/www/html for all unmatched domains.
Waiting for verification...
Cleaning up challenges

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/example.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/example.com/privkey.pem
   Your cert will expire on 2019-08-21. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot
   again. To non-interactively renew *all* of your certificates, run
   "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le
```

#nextcloud用データベースを作成

以下を実行

```.bash
$sudo mysql
>create database nextcloud;
>grant all privileges on nextcloud.* to 'ncadmin'@'localhost' identified by 'password';
>exit;
```

#nginx設定ファイルをnextcloud用に再設定
https://docs.nextcloud.com/server/16/admin_manual/installation/nginx.html
先ほど作成した設定ファイルを削除しNextcloud用に設定ファイルを作成し直します。

```.bash
$sudo rm /etc/nginx/sites-enabled/default
$sudo nano /etc/nginx/sites-enabled/default
```

以下をコピペして貼り付ける

```default
upstream php-handler {
    #server 127.0.0.1:9000;
    server unix:/var/run/php/php7.2-fpm.sock;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    # enforce https
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com;

    # Use Mozilla's guidelines for SSL/TLS settings
    # https://mozilla.github.io/server-side-tls/ssl-config-generator/
    # NOTE: some settings below might be redundant
　　ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
　　ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this
    # topic first.
    #add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;
    add_header Referrer-Policy no-referrer;

    # Remove X-Powered-By, which is an information leak
    fastcgi_hide_header X-Powered-By;

    # Path to the root of your installation
    root /var/www/;

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

    # The following 2 rules are only needed for the user_webfinger app.
    # Uncomment it if you're planning to use this app.
    # rewrite ^/.well-known/host-meta /nextcloud/public.php?service=host-meta
    # last;
    #rewrite ^/.well-known/host-meta.json
    # /nextcloud/public.php?service=host-meta-json last;

    # The following rule is only needed for the Social app.
    # Uncomment it if you're planning to use this app.
    # rewrite ^/.well-known/webfinger /nextcloud/public.php?service=webfinger last;

    location = /.well-known/carddav {
      return 301 $scheme://$host/nextcloud/remote.php/dav;
    }
    location = /.well-known/caldav {
      return 301 $scheme://$host/nextcloud/remote.php/dav;
    }

    location /.well-known/acme-challenge { }

    location ^~ /nextcloud {

        # set max upload size
        client_max_body_size 512M;
        fastcgi_buffers 64 4K;

        # Enable gzip but do not remove ETag headers
        gzip on;
        gzip_vary on;
        gzip_comp_level 4;
        gzip_min_length 256;
        gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
        gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

        # Uncomment if your server is build with the ngx_pagespeed module
        # This module is currently not supported.
        #pagespeed off;

        location /nextcloud {
            rewrite ^ /nextcloud/index.php$request_uri;
        }

        location ~ ^\/nextcloud\/(?:build|tests|config|lib|3rdparty|templates|data)\/ {
            deny all;
        }
        location ~ ^\/nextcloud\/(?:\.|autotest|occ|issue|indie|db_|console) {
            deny all;
        }

        location ~ ^\/nextcloud\/(?:index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+)\.php(?:$|\/) {
            fastcgi_split_path_info ^(.+?\.php)(\/.*|)$;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
            fastcgi_param HTTPS on;
            #Avoid sending the security headers twice
            fastcgi_param modHeadersAvailable true;
            fastcgi_param front_controller_active true;
            fastcgi_pass php-handler;
            fastcgi_intercept_errors on;
            fastcgi_request_buffering off;
        }

        location ~ ^\/nextcloud\/(?:updater|oc[ms]-provider)(?:$|\/) {
            try_files $uri/ =404;
            index index.php;
        }

        # Adding the cache control header for js and css files
        # Make sure it is BELOW the PHP block
        location ~ ^\/nextcloud\/.+[^\/]\.(?:css|js|woff2?|svg|gif)$ {
            try_files $uri /nextcloud/index.php$request_uri;
            add_header Cache-Control "public, max-age=15778463";
            # Add headers to serve security related headers  (It is intended
            # to have those duplicated to the ones above)
            # Before enabling Strict-Transport-Security headers please read
            # into this topic first.
            # add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
            add_header X-Content-Type-Options nosniff;
            add_header X-XSS-Protection "1; mode=block";
            add_header X-Robots-Tag none;
            add_header X-Download-Options noopen;
            add_header X-Permitted-Cross-Domain-Policies none;
            add_header Referrer-Policy no-referrer;

            # Optional: Don't log access to assets
            access_log off;
        }

        location ~ ^\/nextcloud\/.+[^\/]\.(?:png|html|ttf|ico|jpg|jpeg)$ {
            try_files $uri /nextcloud/index.php$request_uri;
            # Optional: Don't log access to other assets
            access_log off;
        }
    }
}
```

続けて、該当行を以下のように修正します。

```

server_name example.com 192.168.1.12;　#ローカルからもアクセスする場合はローカルipアドレスもドメインとして追加

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
```

設定を更新する

```.bash
$sudo nginx -t
$sudo nginx -s reload
```

外部ネットワークから http://example.com にアクセスしnginxから何らかのレスポンスが帰ってくれば成功です。

#nextcloud16のインストール
以下を実行

```.bash
$cd
$wget https://download.nextcloud.com/server/releases/nextcloud-16.0.1.zip
$unzip nextcloud-16.0.1.zip
$sudo mv nextcloud /var/www/nextcloud
$sudo chown -R www-data:www-data /var/www/
```

#nextcloudにアクセスする
最後にhttps://example.com/nextcloud にアクセスし，セットアップを完了します。


| 項目名       |       入力する値 |    
|:-----------------|:------------------:|
| Username             |自分で決めて入力 |
| Password           |   自分で決めて入力 |
| Data folder             | /var/www/html/nextcloud/data |   
|Database user | ncadmin |      
| Database password  | password |   
| Database name|nextcloud | 
|localhost|localhost|

Finish Setupを押下し,設定完了までしばらく待てば終了です。
あとはご自身でサイトにアクセスし，お好きなファイルをアップロードしてください。

#終わりに
サーバー容量を気にせず何でもアップロードできるようになったので，出先から自宅のコンテンツを好きに楽しめるようになり，大変満足です。

#参考サイト
https://www.howtoforge.com/tutorial/ubuntu-nginx-nextcloud/
https://heartbeats.jp/hbblog/2012/06/nginx06.html#more
https://qiita.com/yudsuzuk/items/83115236e9ca184326d2
http://www.sasapy.com/raspi/raspbian_nginx_php70/
http://hidekazu.hatenablog.jp/entry/2017/07/22/172909
https://www.yoheim.net/blog.php?q=20171204