LoginSignup
26

More than 3 years have passed since last update.

さくらVPSで、SSL+CentOS7+Nginx+PHP7+MySQLを構築する方法

Last updated at Posted at 2017-09-20

公開鍵でのログイン設定

流れはおおざっぱに以下となる。

  1. さくらVPSにユーザーを作成
  2. ローカルで公開鍵/秘密鍵を作成
  3. 作成した秘密鍵を、どのIPへの接続に使うかを設定
  4. さくらVPSに公開鍵を設置
  5. さくらVPSに作成したユーザーで、さくらVPSにsshログイン

1. さくらVPSにユーザーを作成

さくらVPSにsshログイン。

$ ssh root@xxx.xxx.xxx.xxx

OSをインストールしたばかりだと、パッケージが最新のバージョンになってない場合があるため更新しましょう。

$ yum -y update

ユーザーを作成。

useradd pikachuu
passwd pikachuu

作成したユーザーに権限を付与。

$ visudo

以下の内容にして保存。

root        ALL=(ALL)       ALL
pikachuu    ALL=(ALL)       ALL (追加行)

2. ローカルで公開鍵/秘密鍵を作成

ローカル環境で、公開鍵と秘密鍵を作成。

$ cd ~/.ssh
$ ssh-keygen -t rsa -f sakura_vps_rsa

3. 作成した秘密鍵を、どのIPへの接続に使うかを設定

ssh設定ファイルに、さくらVPSに接続する際に作成した秘密鍵を使うように設定。

$ vim ~/.ssh/config

以下を追記して保存。

Host sakrua_vps
  Hostname さくらVPSのIP
  Port 22
  User pikachuu
  IdentityFile ~/.ssh/sakura_vps_rsa

4. さくらVPSに公開鍵を設置

ローカルで作成した公開鍵を表示して、全部コピー。

$ cat sakura_vps_rsa.pub

さくらVPSに作成したユーザーでログインし、公開鍵を設置

$ ssh pikachuu@xxx.xxx.xxx.xxx
$ mkdir .ssh
$ chmod 700 .ssh
$ cd .ssh
$ vim authorized_keys
{コピーした公開鍵(sakura_vps_rsa.pub)をペースト}
$ chmod 600 authorized_keys
$ exit

5. さくらVPSに作成したユーザーで、さくらVPSにsshログイン

これで、パスワード入力なしで、作成した鍵でsshログインできる。

$ ssh sakura_vps

firewalldの設定

最初はssh接続しか許可されていないため、ブラウザでさくらVPSのIPにアクセスしても何も帰ってこない。
そのため、http接続を許可する必要がある。

まずは、CentOS7のfirewalldの設定を確認。

$ firewall-cmd --list-all
public (default, active)
  interfaces: eth0
  sources: 
  services: dhcpv6-client ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 

http接続許可設定を追加。

$ firewall-cmd --add-service=http --permanent

firewalldの設定を反映。

$ firewall-cmd --reload

http接続の許可が反映されているか確認。

$ firewall-cmd --list-all
public (default, active)
  interfaces: eth0
  sources: 
  services: dhcpv6-client http ssh
  ports: 
  masquerade: no
  forward-ports: 
  icmp-blocks: 
  rich rules: 

OS再起動

$ shutdown -r now

Nginx

Nginxの最新版をインストールするために、レポジトリにnginxの設定を追加。

$ ssh sakura_vps
$ sudo vi /etc/yum.repos.d/nginx.repo

下記を記述して保存。

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=0
enabled=0

nginxをインストール。

$ sudo yum -y install nginx

nginxを起動し、サービスに追加。

$ sudo systemctl start nginx
$ sudo systemctl enable nginx.service

PHP7 + php-fpm

さくらVPSで、PHP7 + php-fpmをインストール。

$ sudo yum install epel-release
(EPELリポジトリの追加。)
$ rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
(Remiリポジトリの追加)
$ yum -y install --enablerepo=remi,remi-php73 php php-devel php-mbstring php-pdo php-gd php-zip php-xml  php-mysql
(PHP7.3インストール)

php-fpmの編集。

$ vi /etc/php-fpm.d/www.conf

apacheではなく、nginxに変更。

user = nginx
group = nginx

php-fpmを起動、サービスに追加。

$ sudo systemctl start php-fpm
$ sudo systemctl enable php-fpm.service

これで ブラウザにアクセスすると、nginxのページが表示されます。

Nginxの設定を更新

$ vim /etc/nginx/nginx.conf

以下、Codeigniterを使った場合の設定例。

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    server_tokens       off;

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

    index   index.php index.html index.htm;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  {ホスト};
        root         /var/www/html/codeigniter_project;
        index index.html index.php;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
            expires 15d;
            log_not_found off;
        }

        location / {
            # Check if a file or directory index file exists, else route it to index.php.
            try_files $uri $uri/ /index.php;
        }

        location ~* \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            include fastcgi.conf;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

MySQL

mariaDBを削除。

$ yum remove mariadb-libs
$ rm -rf /var/lib/mysql/

MySQLのレポジトリを追加。
(CentOS7では、MySQLレポジトリが提供されていない。)

$ yum localinstall http://dev.mysql.com/get/mysql57-community-release-el7-7.noarch.rpm

MySQLをインストール。

$ yum install mysql-community-server

MySQLを起動し、サービスに追加。

$ systemctl start mysqld.service
$ systemctl enable mysqld.service

MySQLのセキュリティを設定

$ mysql_secure_installation

my.cnf更新

$ vim /etc/my.cnf
character-set-server = utf8
default_password_lifetime = 0

MySQLユーザーを追加。

$ mysqladmin -u root password <your password>

mysql> CREATE USER <user_name> IDENTIFIED BY 'password';

rootユーザーで、databaseを作成。

$ mysql -uroot -p
mysql> create database test_table;
mysql> GRANT ALL PRIVILEGES ON test_table.* TO <user_name>@localhost IDENTIFIED BY 'password';

起動などに問題があればここをチェック

$ tail -f /var/log/mysqld.log

SSL

Let's Encryptを導入。

$ su
$ cd ~
$ git clone https://github.com/certbot/certbot
$ cd ~/certbot
$ ./certbot-auto -debug

SSL証明書を発行。

./certbot-auto certonly

nginxを停止。

$ systemctl stop nginx.service

停止できてるか確認。

$ netstat -lntp

停止できてない場合は、apacheが動いてたり、nginxをサービスに追加してるので勝手に起動してる可能性があります。
その場合は、このようにします。

$ systemctl stop httpd
$ systemctl enable nginx.service

nginxの設定を更新。

$ vim /etc/nginx/nginx.conf

以下を追記。

server {
    listen       443 ssl http2 default_server;
    listen       [::]:443 ssl http2 default_server;
    server_name  {ホスト};
    root         /var/www/html/codeigniter_project;

    ssl_certificate      /etc/letsencrypt/live/{ドメイン}/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/{ドメイン}/privkey.pem;
    ssl_session_cache shared:SSL:1m;
    ssl_session_timeout  10m;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    include /etc/nginx/default.d/*.conf;

    location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
       expires 15d;
       log_not_found off;
    }

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~* \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi.conf;
    }

    error_page 404 /404.html;
        location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}

SSL自動更新

以下をcronに追加。

分 時 日 月 週 root /root/certbot/certbot-auto renew --post-hook "systemctl restart nginx.service"

セッションが保存されないとき

chown -R nginx.nginx /var/lib/php/session/

ファイルをアップロード可能にする

/etc/php.ini

upload_max_filesize = 20M
memory_limit = 256M
post_max_size = 20M
sudo systemctl restart php-fpm

必要だったら nginx.confも更新

client_max_body_size 20M ← 追記
sudo service nginx restart

Composer をインストール

curl https://getcomposer.org/installer | php
mv -i composer.phar /usr/local/bin/composer

参考

ssl設定をしてからnginxを再起動しようとしたらエラーになったのですが、こちらが役に立ちました。

Sep 24 19:40:47 localhost.localdomain nginx[12707]: nginx: configuration file /etc/nginx/nginx.conf...ful 
Sep 24 19:40:47 localhost.localdomain nginx[12709]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98:...se) 
Sep 24 19:40:47 localhost.localdomain nginx[12709]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98:...se) 
Sep 24 19:40:48 localhost.localdomain nginx[12709]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98:...se) 
Sep 24 19:40:48 localhost.localdomain nginx[12709]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98:...se) 
Sep 24 19:40:49 localhost.localdomain nginx[12709]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98:...se) 
Sep 24 19:40:49 localhost.localdomain nginx[12709]: nginx: [emerg] still could not bind() 

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
26