科学上网和学习笔记

最开始只是想用来科学上网,于是在搬瓦工上租了个服务器;后来觉得仅仅这样有点浪费,就顺便又弄了个wordpress,记点笔记。

准备工作

首先在搬瓦工上注册账号,信息尽量真实,比如国家,否则后面可能会被认为欺诈,没收服务器,亲身体验~~
然后购买适合自己的VPS,购买前最好看看support->Knowledgebase。如果需要运行wordpress最好选择512M以上内存。
购买成功后可以在services->My services里看到,点击KiwiVM Control Panel可以进入控制台。
在控制台里乱搞一通后就熟悉了。

账户安全

重装系统,使用centos7。
新建用户并配置证书ssh登录,保存私钥到本地。

yum install lrzsz  #可视情况跳过
useradd -m newuser
su newuser
cd ~
ssh-keygen -t rsa #此处执行过程中最好定义通行短语
cd .ssh/
sz id_rsa #这个私钥保存好
cat id_rsa.pub >> ~/.ssh/authorized_keys

新用户免密码su root,禁用密码登录,禁用root用户ssh登录。

vi /etc/pam.d/su
去掉注释 #auth           sufficient      pam_wheel.so trust use_uid
usermod -G wheel newuser
vim /etc/ssh/sshd_config
修改以下属性
PermitRootLogin no
RSAAuthentication yes
PubkeyAuthentication yes
StrictModes no
PasswordAuthentication no

语言环境

修改为UTF-8,以便使用中文

localectl status
localectl list-locales
localectl set-locale LANG=en_US.UTF-8
vi /etc/locale.conf
LANG=en_US.UTF-8

安装Shadowsocks Server

其实可以直接在控制台里安装ShadowsocksServer。但不支持centos7,所以选择自行安装。
参考:
https://github.com/shadowsocks/shadowsocks/tree/master
http://www.leyar.me/install-the-shadowsocks/

安装

yum install python-setuptools && easy_install pip
pip install shadowsocks

创建配置文件 /etc/ss-config.json

{
    "server":"0.0.0.0",
    "server_port":29292,
    "local_address":"127.0.0.1",
    "local_port":4949,
    "password":"mypwd",
    "timeout":300,
    "method":"aes-256-cfb",
    "fast_open":false
}

创建系统服务文件 /etc/systemd/system/shadowsocks-server.service

[Unit]
Description=Shadowsocks Server
After=network.target

[Service]
Type=forking
PIDFile=/var/run/shadowsocks/server.pid
PermissionsStartOnly=true
ExecStartPre=/bin/mkdir -p /var/run/shadowsocks
ExecStartPre=/bin/chown root:root /var/run/shadowsocks
ExecStart=/usr/bin/ssserver --pid-file /var/run/shadowsocks/server.pid -c /etc/ss-config.json -d start --user nobody
Restart=on-abort
User=root
Group=root
UMask=0027

[Install]
WantedBy=multi-user.target

设置权限并注册自启服务

cd /etc/systemd/system
chmod 755 shadowsocks-server.service
systemctl start shadowsocks-server.service
systemctl enable shadowsocks-server.service

安装PHP

安装并注册自启服务

yum install php php-mysql php-fpm
systemctl start php-fpm
systemctl enable php-fpm

创建安全配置文件 /etc/php.d/security.ini

# php info hide
expose_php=Off

# error hide
display_errors=Off
log_errors=On
error_log=/var/log/httpd/php_scripts_error.log

# upload Off
#file_uploads=Off
file_uploads=On
upload_max_filesize=5M

# romote code exec Off
allow_url_fopen=Off

# romote url include Off
allow_url_include=Off

# post size limit
post_max_size=10240K

# resource ctl
max_execution_time=30
max_input_time=30
memory_limit=40M

# disable dangerous func
disable_functions=exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

优化php-fpm配置,参考 https://segmentfault.com/a/1190000004190979

vi /etc/php-fpm.conf
#修改以下参数
emergency_restart_threshold = 60
emergency_restart_interval = 1m
vi /etc/php-fpm.d/www.conf
#修改以下参数
pm.max_children = 12
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10

安装Maria

安装并注册自启服务

yum install mariadb-server mariadb
systemctl enable mariadb.service
systemctl start mariadb.service

初始化

mysql_secure_installation  #执行过程中设置各参数,记住root用户密码

为wordpress创建数据库,新建数据库用户并分配权限

mysql -uroot -prootpwd --default-character-set=utf8
CREATE DATABASE wordpress;
USE mysql;
CREATE USER 'wpuser'@'localhost' IDENTIFIED BY 'wpuserpwd';
GRANT ALL PRIVILEGES ON  wordpress.* TO 'wpuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

安装Nginx

安装并注册自启服务

yum search nginx  #可视情况跳过
yum install epel-release  #可视情况跳过
yum install nginx
systemctl start nginx
systemctl enable nginx

修改配置文件 /etc/nginx/nginx.conf

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

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;

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

    # 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         /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 {
#        }
#    }
}

修改配置文件 /etc/nginx/conf.d/wordpress.conf,这是wordpress服务的配置

# Redirect everything to the main site. We use a separate server statement and NOT an if statement - see http://wiki.nginx.org/IfIsEvil
#server {
#    server_name  _;
#    rewrite ^ $scheme://xxx.xxx.xxx.xxx$request_uri redirect;
#}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name xxx.xxx.xxx.xxx;
    root /mnt/wordpress;

    # Global restrictions configuration.
    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }
    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
    # Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
    location ~ /\. {
        deny all;
    }

    # Deny access to any files with a .php extension in the uploads directory
    # Works in sub-directory installs and also in multisite network
    # Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
    location ~* /(?:uploads|files)/.*\.php$ {
        deny all;
    }

    # WordPress single blog rules.

    # This order might seem weird - this is attempted to match last if rules below fail.
    # http://wiki.nginx.org/HttpCoreModule
    location / {
        index        index.php index.html index.htm;
        try_files $uri $uri/ /index.php?$args;
    }

    # Add trailing slash to */wp-admin requests.
    rewrite /wp-admin$ $scheme://$host$uri/ permanent;

    # Directives to send expires headers and turn off 404 error logging.
    location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
        access_log off; log_not_found off; expires max;
    }
 
    # Pass all .php files onto a php-fpm/php-fcgi server.
    location ~ \.php$ {
        # Zero-day exploit defense.
        # http://forum.nginx.org/read.php?2,88845,page=3
        # Won't work properly (404 error) if the file is not stored on this server, which is entirely possible with php-fpm/php-fcgi.
        # Comment the 'try_files' line out if you set up php-fpm/php-fcgi on another machine.  And then cross your fingers that you won't get hacked.
        try_files $uri =404;
     
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
     
        include fastcgi_params;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    #   fastcgi_intercept_errors on;
        fastcgi_pass 127.0.0.1:9000;
    }

}

安装Wordpress

下载并解压

cd /mnt
wget https://cn.wordpress.org/wordpress-4.4.2-zh_CN.tar.gz
tar zxvf wordpress-4.4.2-zh_CN.tar.gz
rm -f wordpress-4.4.2-zh_CN.tar.gz
cd wordpress/
find . -type d -exec chmod +x {} \;
find . -name "*.php" -exec chmod +x {} \;

当现在为止应该可以访问 http://xxx.xxx.xxx.xxx/wp-admin/ 进入安装引导界面,如果不行重启下所有服务试试。
安装完成后检查下管理平台的功能是否都好使。

WordPress使用技巧

  • 更换域名,登录maria执行以下sql
use wordpress;
UPDATE wp_options SET option_value = replace( option_value, 'http://xxx.xxx.xxx.xxx', 'https://www.wanghengbin.com') WHERE option_name = 'home' OR option_name ='siteurl';
UPDATE wp_posts SET post_content = replace(post_content, 'http://xxx.xxx.xxx.xxx', 'https://www.wanghengbin.com');
UPDATE wp_posts SET guid = replace( guid, 'http://xxx.xxx.xxx.xxx', 'https://www.wanghengbin.com' );
  • 增强文章编辑器,修改当前使用的主题目录下的function.php(注意是主题目录下的),增加以下代码
function add_editor_buttons($buttons) {
$buttons[] = 'fontselect';
$buttons[] = 'fontsizeselect';
$buttons[] = 'cleanup';
$buttons[] = 'styleselect';
$buttons[] = 'del';
$buttons[] = 'sub';
$buttons[] = 'sup';
$buttons[] = 'copy';
$buttons[] = 'paste';
$buttons[] = 'cut';
$buttons[] = 'image';
$buttons[] = 'anchor';
$buttons[] = 'backcolor';
$buttons[] = 'wp_page';
return $buttons;
}
add_filter("mce_buttons_3", "add_editor_buttons");
  • 安装插件,如果安装了ftp可以在管理平台直接安装。也可到官方下载然后自行安装,以syntaxhighlighter为例
cd /mnt/wordpress/wp-content/plugins/
rz -bey syntaxhighlighter.zip
unzip syntaxhighlighter.zip
rm -f syntaxhighlighter.zip
chmod -R +x ./
  • 安装主题,跟安装插件类似
  • 禁用版本修订历史、禁用自动保存修订、清除已有历史

修改wp-config.php,在define(‘WP_DEBUG’, false)行后增加

define( 'AUTOSAVE_INTERVAL', false );  //其实是设置自动保存周期为1天
define( 'WP_POST_REVISIONS', false );

修改wp-admin/post.php和wp-admin/post-new.php,搜索autosave,注释掉相关行。
登录maria执行

select count(*), post_type, post_status from wp_posts group by post_type,post_status;
delete from wp_posts where post_type='revision';
  • 禁用自动保存草稿、清除已有草稿

逻辑:如果获取到数据表中已存在自动草稿则继续使用这个自动草稿而不再添加自动草稿。

修改wp-admin/includes/post.php,找到以下代码

if ( $create_in_db ) {
    $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
    $post = get_post( $post_id );
    if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) )
        set_post_format( $post, get_option( 'default_post_format' ) );
}

修改为:

if ( $create_in_db ) {
    // $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
    // $post = get_post( $post_id );
    global $wpdb;
    global $current_user;
    $post = $wpdb->get_row( "SELECT * FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_status = 'auto-draft' AND {$wpdb->posts}.post_type = '$post_type' AND {$wpdb->posts}.post_author = {$current_user->ID} ORDER BY {$wpdb->posts}.ID ASC LIMIT 1" );  //获取当前表中存在的自动草稿
    if ( !$post ) { // 如果没有找到自动草稿,新建一条
        $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
        $post = get_post( $post_id );
    }
    if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) )
        set_post_format( $post, get_option( 'default_post_format' ) );
}

登录maria执行

select count(*), post_type, post_status from wp_posts group by post_type,post_status;
delete from wp_posts where post_status='auto-draft';
  • 替换自带的分页导航,例如插件wp_pagenavi

安装并启用插件wp_pagenavi
修改主题目录下的index.php
删掉get_next_posts_link和get_previous_posts_link相关,可能不同主题不一样,替换成:

if(function_exists('wp_pagenavi')) { wp_pagenavi();}  //wp_pagenavi(array('wrapper_class'=>'pagination'));
  • 首页摘要

修改主题目录下的content.php(也可能是index.php),将the_content()替换成the_excerpt()
修改主题目录下的functions.php,增加:

function custom_excerpt_length( $length ) {
    return 366;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

function new_excerpt_more( $more ) {
    // return '<a href="' . get_permalink() . '">阅读全文</a>';
    return '';
}
add_filter('excerpt_more', 'new_excerpt_more');
  • 解决部分浏览器查看图片模糊的问题,去掉srcset属性,在主题目录下的function.php中增加:
add_filter( 'wp_calculate_image_srcset_meta', '__return_null' );
  • 查看错误日志,/var/log/php-fpm/www-error.log
  • 定期备份应用和数据
Creative Commons License

本文基于署名-非商业性使用-相同方式共享 4.0许可协议发布,欢迎转载、使用、重新发布,但请保留文章署名wanghengbin(包含链接:https://wanghengbin.com),不得用于商业目的,基于本文修改后的作品请以相同的许可发布。

发表评论