CentOS7搭建Nextcloud

前言

前段时间闲着无聊,想搭建一个本地的NAS,于是发现了Nextcloud项目
本教程不适合无任何Linux基础的人进行查阅

环境准备

CentOS 7.5 最小化安装
网络

PS:由于手头暂时没有设备,于是使用VMware Workstation Pro 14模拟安装

开始

绿色字体为可选步骤
蓝字灰底为输出或者注释
# 以井号开始为root用户执行命令


关闭SELINUX

# vi /etc/sysconfig/selinux
将SELINUX=enforcing改为SELINUX=disabled
保存退出
# setenforce 0
PS:若不进行此步骤,需要进行以下配置
# yum install policycoreutils-python -y
# semanage fcontext -a -t httpd_sys_rw_content_t '/usr/share/nginx/html/nextcloud/data(/.*)?'
# semanage fcontext -a -t httpd_sys_rw_content_t '/usr/share/nginx/html/nextcloud/config(/.*)?'
# semanage fcontext -a -t httpd_sys_rw_content_t '/usr/share/nginx/html/nextcloud/apps(/.*)?'
# semanage fcontext -a -t httpd_sys_rw_content_t '/usr/share/nginx/html/nextcloud/assets(/.*)?'
# semanage fcontext -a -t httpd_sys_rw_content_t '/usr/share/nginx/html/nextcloud/.htaccess'
# semanage fcontext -a -t httpd_sys_rw_content_t '/usr/share/nginx/html/nextcloud/.user.ini'
# restorecon -Rv '/usr/share/nginx/html/nextcloud/'


关闭防火墙

# systemctl stop firewalld
# systemctl disable firewalld
PS:若不执行此步骤,需要进行以下配置
# firewall-cmd --permanent --add-service=http
# firewall-cmd --permanent --add-service=https
# firewall-cmd --reload

更换镜像源

# cd /etc/yum.repos.d/
# cp CentOS-Base.repo CentOS-Base.repo.backup
# vi CentOS-Base.repo
添加以下信息:
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client. You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[base]
name=CentOS-$releasever - Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
baseurl=https://mirrors.ustc.edu.cn/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#released updates
[updates]
name=CentOS-$releasever - Updates
# mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
baseurl=https://mirrors.ustc.edu.cn/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
# mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
baseurl=https://mirrors.ustc.edu.cn/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
baseurl=https://mirrors.ustc.edu.cn/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
# rpm -ivh https://mirrors.ustc.edu.cn/epel/epel-release-latest-7.noarch.rpm
# sed -e 's!^mirrorlist=!#mirrorlist=!g' \
         -e 's!^#baseurl=!baseurl=!g' \
         -e 's!//download\.fedoraproject\.org/pub!//mirrors.ustc.edu.cn!g' \
         -e 's!http://mirrors\.ustc!https://mirrors.ustc!g' \
         -i /etc/yum.repos.d/epel.repo /etc/yum.repos.d/epel-testing.repo
# yum repolist

配置静态IP

# nmcli connection show                                          //查看网卡名
# vi /etc/sysconfig/network-scripts/ifcfg-ens33       //ens33为网卡设备名
修改为如下:
BOOTPROTO=static                                                   //网卡工作模式,static/none为静态,dhcp为动态
DNS1=1.2.4.8                                                             //主DNS地址
DNS2=101.6.6.6                                                         //备用DNS地址
NAME=ens33 
UUID=92d757ee-de16-42cc-bbe0-fc8ebf6e604a     //网卡UUID
DEVICE=ens33                                                           //网卡设备名
ONBOOT=yes                                                            //是否开启此设备
IPADDR=192.168.59.200                                           //IP地址
NETMASK=255.255.255.0                                         //子网掩码
GATEWAY=192.168.59.2                                           //网关

# systemctl restart network                                       //无任何输出即生效

基本配置

安装基本软件包:
# yum install vim bash-completion -y
更新系统:
# yum update -y
重启以应用:
# reboot

重新安装Nginx和Php

卸载php和nginx:
# rpm -qa |grep -E '(php|nginx)'|xargs -i rpm -e --nodeps {}
安装nginx:
# yum install nginx unzip wget -y
安装php:
# rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
# yum repolist
# yum install -y php70w-devel php70w-pear php70w-pecl php70w-gd php70w-opcache php70w-cli php70w-pdo php70w-process php70w-pecl-apcu php70w-mcrypt php70w-mysql php70w-fpm php70w-pecl-memcached php70w-common php70w-xml php70w-mbstring php70w-pecl-igbinary
PS:php70w-fpm这个软件包可能会没有,不过不影响
检查安装是否成功:
# nginx -v
nginx version: nginx/1.12.2
# php -v
PHP 7.0.33 (cli) (built: Dec  6 2018 22:30:44) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33, Copyright (c) 1999-2017, by Zend Technologies

安装和配置数据库

安装MySQL:
# yum install mariadb-server -y
启动数据库和开启开机自启动:
# systemctl start mariadb
# systemctl enable mariadb
初始化:
# mysql_secure_installation
(MySQL初始化省略)
进入数据库,"123456"为初始化时设置的密码:
# mysql -uroot -p123456
> create database nextcloud_db;
//授权给自定义用户,这里以用户名:nextclouduser,密码:nextcloudpasswd 进行代替
> grant all privileges on nextcloud_db.* to nextclouduser@localhost identified by 'nextcloudpasswd';
> flush privileges;
>exit;

生成证书

为Nextcloud 生成自签名ssl证书:
# mkdir /etc/nginx/cert
# cd /etc/nginx/cert
生成证书:
# openssl req -new -x509 -days 365 -nodes -out /etc/nginx/cert/nextcloud.crt -keyout /etc/nginx/cert/nextcloud.key
会出现下面的选项需要填写,可以随便填
Country Name (2 letter code) [XX]:CN                                                        //国家
State or Province Name (full name) []:Hunan                                             //省份
Locality Name (eg, city) [Default City]:Changsha                                        //地区名字
Organization Name (eg, company) [Default Company Ltd]: (Enter)           //公司名
Organizational Unit Name (eg, section) []:(Enter)                                       //部门
Common Name (eg, your name or your server's hostname) []:(Enter)       //CA主机名
Email Address []:(Enter)                                                                               //Email地址
修改权限:
# chmod 600 /etc/nginx/cert/*
# chmod 700 /etc/nginx/cert

安装Nextcloud及其基本配置

# cd /tmp
# wget https://download.nextcloud.com/server/releases/nextcloud-15.0.2.zip
# unzip nextcloud-15.0.2.zip
# mv nextcloud /usr/share/nginx/html/
创建数据文件夹:
# mkdir /usr/share/nginx/html/nextcloud/data
更改权限:
# chown nginx:nginx -R /usr/share/nginx/html/nextcloud/
配置php-fpm:
# vim /etc/php-fpm.d/www.conf
修改以下两项:
user = nginx
group = nginx
去掉以下五项注释:
env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

# mkdir -p /var/lib/php/session
# chown nginx:nginx -R /var/lib/php/session/

配置nginx

# vim /etc/nginx/conf.d/nextcloud.conf
添加以下代码:
upstream php-handler {
    server 127.0.0.1:9000;
    #server unix:/var/run/php5-fpm.sock;
}
server {
    listen 80;
    server_name localhost;
    # enforce https
    rewrite ^(.*)$ https://$host$1 permanent;
}
server {
    listen 443 ssl;
    server_name localhost;
    ssl_certificate /etc/nginx/cert/nextcloud.crt;
    ssl_certificate_key /etc/nginx/cert/nextcloud.key;
    # 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-Frame-Options "SAMEORIGIN";
    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;
    # Path to the root of your installation
    root /usr/share/nginx/html/nextcloud/;
    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 /public.php?service=host-meta last;
    #rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json
    # last;
    location = /.well-known/carddav {
      return 301 $scheme://$host/remote.php/dav;
    }
    location = /.well-known/caldav {
      return 301 $scheme://$host/remote.php/dav;
    }
    # set max upload size
    client_max_body_size 512M;    #默认为512M,上传文件最大限制,php.ini中也要修改
    fastcgi_buffers 64 4K;
    # Disable gzip to avoid the removal of the ETag header
    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;
    error_page 403 /core/templates/403.php;
    error_page 404 /core/templates/404.php;
    location / {
        rewrite ^ /index.php$uri;
    }
    location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ {
        deny all;
    }
    location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
        deny all;
    }
    location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+|core/templates/40[34])\.php(?:$|/) {
        include fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        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 ~ ^/(?:updater|ocs-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 ~* \.(?:css|js)$ {
        try_files $uri /index.php$uri$is_args$args;
        add_header Cache-Control "public, max-age=7200";
        # 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-Frame-Options "SAMEORIGIN";
        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;
        # Optional: Don't log access to assets
        access_log off;
    }
    location ~* \.(?:svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$ {
        try_files $uri /index.php$uri$is_args$args;
        # Optional: Don't log access to other assets
        access_log off;
    }
}

# vim /etc/nginx/nginx.conf
将以下片段删除或注释:
server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  _;
    root         /usr/share/nginx/html;

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

    location / {
    }

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

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

检测nginx配置文件:
# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
启动服务和设置开机自启动:
# systemctl start nginx.service 
# systemctl enable nginx.service 
# systemctl start php-fpm
# systemctl enable php-fpm

访问IP即可

Nextcloud

报错:

使用Chrome访问可能会出现如下问题:
Chrome访问报错
换浏览器就好了,具体的原因不清楚

评论

此博客中的热门博文

各Linux发行版桌面环境与上手舒适度横向评测

文件完整性校验的必要性

写在前面