EC2
sudo su -l
passwd ec2-user
timedatectl set-timezone Asia/Tokyo
cp -rp /etc/sysconfig/clock /etc/sysconfig/clock.org
/etc/sysconfig/clock
-ZONE="UTC"
-UTC=true
+ZONE="Asia/Tokyo"
+UTC=false
/etc/sysconfig/i18n
-LANG=en_US.UTF-8
+LANG=ja_JP.UTF-8
dnf update
#cron
dnf install -y cronie
#rsyslog
dnf install -y rsyslog
#nginx
dnf install -y nginx
nginx -v
#nginx version: nginx/1.28.0
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.org
#php8.4
# dnf list --available php8.4*
dnf install -y php8.4 php8.4-fpm php8.4-bcmath php8.4-common php8.4-cli php8.4-pdo php8.4-mysqlnd php8.4-gd php8.4-mbstring php8.4-opcache php8.4-devel php8.4-xml php8.4-intl php8.4-zip
php -v
#PHP 8.4.13 (cli)
systemctl start php-fpm
systemctl enable php-fpm.service
#imagick
dnf install -y ImageMagick-devel php-pear
pecl install imagick
PHP
/etc/php.ini
date.timezone = "Asia/Tokyo"
memory_limit = 256M
expose_php = Off
post_max_size = 8M
upload_max_filesize = 4M
#memory_limit > post_max_size > upload_max_filesize
#3 days
session.gc_maxlifetime = 259200
#7 days
#session.gc_maxlifetime = 604800
#session.name = PHPSESSID
#session.cookie_lifetime = 0
[mbstring]
mbstring.language = Japanese
[imagick]
extension=imagick.so
/etc/php-fpm.d/www.conf
-user = apache
+user = nginx
-group = apache
+group = nginx
phpMyAdmin
cd /var/www/
wget https://files.phpmyadmin.net/phpMyAdmin/5.2.1/phpMyAdmin-5.2.1-all-languages.tar.gz
tar zxvf phpMyAdmin-5.2.1-all-languages.tar.gz
rm phpMyAdmin-5.2.1-all-languages.tar.gz
mv phpMyAdmin-5.2.1-all-languages phpmyadmin
cd /var/www/phpmyadmin/
cp config.sample.inc.php config.inc.php
/var/www/phpmyadmin/config.inc.php
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'http';//BASIC認証
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
Nginx
/etc/nginx/snippets/block-sqli.conf
# SQLインジェクションの典型的な文字列を含むリクエストを拒否
set $block_sqli 0;
if ($request_uri ~* "sleep\s*(\(|%28)|benchmark\s*(\(|%28)|waitfor(%20|\+|\s)+delay|union(%20|\+|\s)+(all(%20|\+|\s)+)?select|information_schema|sysdate\s*(\(|%28)") {
set $block_sqli 1;
}
if ($http_user_agent ~* "sleep\s*\(|benchmark\s*\(|waitfor\s+delay|union\s+(all\s+)?select|information_schema|sysdate\s*\(") {
set $block_sqli 1;
}
if ($block_sqli) {
return 403;
}
/etc/nginx/snippets/block-bots.conf
# 拒否するボット・ツール(ユーザーエージェント)
if ($http_user_agent ~* "WebSiphon|ShapBot|SERankingBacklinksBot|AwarioBot|AhrefsBot|SemrushBot|DotBot|TalarionSearchBot|QlyzeBot|SleepBot|libwww-perl|Bytespider") {
return 403;
}
# 多数のIPに分散して、ページを総当たりで取得するツール
if ($http_user_agent ~ "Chrome/104\.0\.0\.0 Safari/537\.36$") {
return 403;
}
# 攻撃元のIP
deny 36.101.143.212;
deny 45.148.10.12;
deny 77.83.25.111;
deny 194.110.115.14;
deny 168.144.108.17;
deny 103.77.107.178;
deny 163.52.135.238;
deny 67.205.184.94;
deny 103.155.64.115;
deny 94.102.56.8;
deny 164.92.98.27;
deny 68.210.80.119;
deny 185.254.75.35;
deny 142.4.122.238;
/etc/nginx/snippets/block-files.conf
# バックアップのファイルを探すスキャン対策:存在しなければ、PHPに渡さずに404
location ~* \.(zip|rar|7z|tgz|tar|gz|bz2|xz|apk|bak|old|backup|sql|swp)$ {
try_files $uri =404;
}
# ドットファイルはすべて拒否(Let's Encrypt の証明書更新で使う /.well-known/ は除外)
location ~ /\.(?!well-known) {
deny all;
}
/etc/nginx/nginx.conf
events {
worker_connections 1024;
}
http {
# アクセスログの形式
# rt= リクエスト全体にかかった時間(秒)
# urt= PHPの処理にかかった時間(秒)。PHPに渡さなかったもの(キャッシュや静的ファイル)は -
# cache= キャッシュの状態(HIT=キャッシュから返した、MISS・EXPIRED=PHPで作った、BYPASS=キャッシュを使わない条件に当てはまった、-=キャッシュの対象外)
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" rt=$request_time urt=$upstream_response_time cache=$upstream_cache_status';
index index.php;
charset UTF-8;
server_tokens off;
# gzip 圧縮(JSON・CSS・JS などのテキストを圧縮して転送量を減らす)
gzip on;
gzip_vary on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_proxied any;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml image/svg+xml;
#FastCGI CACHE
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=FCKZ:32m inactive=1d max_size=128m;
fastcgi_cache_use_stale error timeout invalid_header http_500;
server {
listen 80;
listen [::]:80;
server_name example.com;
root /usr/share/nginx/html;
#root /var/www/html;
client_max_body_size 4m;
#include /etc/nginx/default.d/*.conf;
if ($host != "example.com") {
return 301 https://example.com$request_uri;
}
# SQLインジェクションの典型的な文字列を含むリクエストを拒否
include /etc/nginx/snippets/block-sqli.conf;
# 拒否するボットと攻撃元のIP
include /etc/nginx/snippets/block-bots.conf;
# 拒否するファイル(バックアップのファイル、ドットファイル)
include /etc/nginx/snippets/block-files.conf;
# wp-config.php への直接のアクセスを拒否
location = /wp-config.php {
deny all;
}
# Login rebuilderなどでログインURLを変更している場合
# パスワード保護の記事のパスワード入力(action=postpass)だけはPHPへ渡す
location = /wp-login.php {
if ($arg_action != "postpass") {
return 403;
}
fastcgi_pass php-fpm;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location = /xmlrpc.php {
deny all;
return 403;
}
#FastCGI CACHE
set $do_not_cache 0;
if ($request_method !~ ^(GET)$) {
set $do_not_cache 1;
}
if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
set $do_not_cache 1;
}
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
set $do_not_cache 1;
}
fastcgi_cache_key "$scheme://$host$request_uri";
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php{
try_files $uri =404;
fastcgi_pass php-fpm;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_script_name;
include fastcgi_params;
fastcgi_cache_bypass $do_not_cache;
fastcgi_no_cache $do_not_cache;
fastcgi_cache FCKZ;
#キャッシュがないページに同時にアクセスが来ても、PHPを動かすのは最初の1件だけ。残りはその結果を待つ
fastcgi_cache_lock on;
fastcgi_cache_lock_timeout 5s;
fastcgi_cache_use_stale updating error timeout invalid_header http_500 http_503;
fastcgi_cache_background_update on;
fastcgi_cache_valid 200 5m;
fastcgi_cache_valid any 10m;
fastcgi_pass_header X-Accel-Expires;
fastcgi_ignore_headers Cache-Control Expires;
add_header x-cache $upstream_cache_status;
}
location ~* \.(jpe?g|gif|png|css|js|flv|swf|ico|xml|txt|eot|svg|ttf|woff|woff2)$ {
try_files $uri /index.php?$args;
access_log off;
log_not_found off;
expires 7d;
}
}
# 443は後述のLet's Encryptがやってくれるんで追記するやつがあれば
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name _;
location ^~ /phpmyadmin {
#allow 0.0.0.0;#IP制限
deny all;
alias /var/www/phpmyadmin;
index index.php;
location ~ \.php {
fastcgi_pass php-fpm;
fastcgi_index index.php;
fastcgi_split_path_info ^/phpmyadmin(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME /var/www/phpmyadmin$fastcgi_script_name;
include /etc/nginx/fastcgi_params;
}
}
}
}
nginx -t && systemctl start nginx
# nginx -t && systemctl reload nginx
systemctl enable nginx.service
再起動設定
/lib/systemd/system/nginx.service
[Service]
+Restart=always
+RestartSec=5s
systemctl daemon-reload
systemctl restart nginx
systemctl show nginx | grep Restart
Git
dnf install -y git
#GitHub
cd /var/www/
git clone https://github.com/[path_to_git].git html
chown -R nginx:nginx /var/lib/php/session
chown -R nginx:nginx /var/www/html
確認
/usr/share/nginx/html/phpinfo.php
<?php
phpinfo();
Let's Encrypt
dnf install -y certbot
dnf install -y python3-certbot-nginx
certbot --version
certbot --nginx --agree-tos --register-unsafely-without-email
crontab
# At 03:00, 15:00
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
0 3,15 * * * certbot renew --deploy-hook "systemctl reload nginx" >> /var/log/certbot-renew.log 2>&1
sudo tee /etc/logrotate.d/certbot-renew > /dev/null <<'EOF'
# certbot 自動更新(crontab)の実行ログのローテーション
/var/log/certbot-renew.log {
weekly
rotate 12
missingok
notifempty
compress
delaycompress
create 0640 root root
}
EOF
sudo logrotate -d /etc/logrotate.d/certbot-renew
Hostname
hostnamectl set-hostname [example]
MariaDB
dnf install -y mariadb114-server mariadb114
/etc/my.cnf.d/mariadb-server.cnf
[mysqld]
+character-set-server = utf8mb4
#インスタンスのメモリに合わせる
+innodb_buffer_pool_size=256M
+max_connections=50
+performance_schema=OFF
/etc/my.cnf.d/client.cnf
[client]
+default-character-set = utf8mb4
systemctl start mariadb
systemctl enable mariadb.service
mariadb --version
DBとユーザーを作成
DB_NAME="dbname"
DB_USER="username"
DB_PASS=$(openssl rand -base64 32 | tr -d '/+=' | cut -c1-24)
mariadb -u root <<EOF
CREATE DATABASE \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';
GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO '${DB_USER}'@'localhost';
FLUSH PRIVILEGES;
SHOW GRANTS FOR '${DB_USER}'@'localhost';
EOF
echo "ユーザー: ${DB_USER}"
echo "パスワード: ${DB_PASS}"
#表示されたパスワードを保管
mariadb -u username -p dbname
#ログインできたらパスワードの変数を削除
unset DB_PASS
サーバーの中(127.0.0.1)からだけ接続を受け付ける
cat > /etc/my.cnf.d/zz-bind.cnf <<'EOF'
[mysqld]
# サーバーの中(127.0.0.1)からだけ接続を受け付ける
bind-address = 127.0.0.1
EOF
cat /etc/my.cnf.d/zz-bind.cnf
systemctl restart mariadb
sleep 3
ss -tlnp | grep 3306
# 127.0.0.1:3306 の1行だけ
落ちても自動で再起動させる
mkdir -p /etc/systemd/system/mariadb.service.d
cat > /etc/systemd/system/mariadb.service.d/override.conf <<'EOF'
[Service]
Restart=on-failure
RestartSec=5s
EOF
systemctl daemon-reload
systemctl show mariadb -p Restart -p RestartUSec
systemctl restart mariadb
WordPress
wget https://ja.wordpress.org/latest-ja.tar.gz
# zsh
# curl https://ja.wordpress.org/latest-ja.tar.gz -O
tar zxvf latest-ja.tar.gz
rm latest-ja.tar.gz
cp -rpf wordpress/* ./
rm -rf wordpress
cp wp-config-sample.php wp-config.php
chmod 640 wp-config.php
wp-config.php
$env = match($_SERVER['HTTP_HOST']) {
'production.com' => 'production',
'staging.com' => 'staging',
default => 'local',
};
$db = match ($env) {
'production' => [
'name' => 'dbname',
'user' => 'dbuser',
'pass' => 'dbpass',
'host' => 'localhost',
],
'staging' => [
'name' => 'dbname',
'user' => 'dbuser',
'pass' => 'dbpass',
'host' => 'localhost',
],
'local' => [
'name' => 'dbname',
'user' => 'dbuser',
'pass' => 'dbpass',
'host' => 'localhost',
],
};
switch ($env) {
case 'production':
define('WP_DEBUG', false);
define('FORCE_SSL_ADMIN', true);
if ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === "https" ) {
$_SERVER['HTTPS'] = 'on';
}
break;
case 'staging':
define('WP_DEBUG', false);
define('FORCE_SSL_ADMIN', true);
if ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === "https" ) {
$_SERVER['HTTPS'] = 'on';
}
break;
default:
define('WP_DEBUG', true);
define('WP_DEBUG_DISPLAY', false);
define('WP_DEBUG_LOG', true);
define('WP_DISABLE_FATAL_ERROR_HANDLER', true);
break;
}
define('WP_ENVIRONMENT_TYPE', $env);
function is_production() {
return ( wp_get_environment_type() === 'production' );
}
function is_staging() {
return ( wp_get_environment_type() === 'staging' );
}
function is_local() {
return ( wp_get_environment_type() === 'local' );
}
define('DB_NAME', $db['name']);
define('DB_USER', $db['user']);
define('DB_PASSWORD', $db['pass']);
define('DB_HOST', $db['host']);
define('DB_CHARSET', 'utf8mb4');
define('DB_COLLATE', '');
WPセキュリティ関連
wp-content/mu-plugins/security.php
<?php
/* ------------------------------------------------------------------
* XML-RPC
* (nginx でも /xmlrpc.php へのアクセスを 403 で拒否)
* ------------------------------------------------------------------ */
// XML-RPC の全メソッドを無効化(xmlrpc_enabled より確実)
add_filter( 'xmlrpc_methods', function () {
return array();
} );
// ヘッダーから XML-RPC / pingback の情報を除去
remove_action( 'wp_head', 'rsd_link' );
add_filter( 'wp_headers', function ( $headers ) {
unset( $headers['X-Pingback'] );
return $headers;
} );
/* ------------------------------------------------------------------
* REST API
* ------------------------------------------------------------------ */
// REST API は、管理画面にログインしているユーザーだけに制限する
// (ログインしていない人に REST API を使わせる機能を追加する場合は、ここを見直す)
add_filter( 'rest_authentication_errors', function ( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
if ( ! is_user_logged_in() ) {
return new WP_Error(
'rest_not_logged_in',
'REST APIへのアクセスには管理画面へのログインが必要です。',
array( 'status' => 401 )
);
}
return $result;
} );
/* ------------------------------------------------------------------
* ユーザー名(ログイン名)の漏えい対策
* ------------------------------------------------------------------ */
// ?author=N や著者ページへのアクセスは、転送せずに 404 にする
// (著者ページへの転送より先に処理するため、優先度を 1 にしている)
add_action( 'template_redirect', function () {
if ( isset( $_GET['author'] ) || is_author() ) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
nocache_headers();
$template = get_404_template();
if ( $template ) {
include $template;
}
exit;
}
}, 1 );
// REST API のユーザー情報は、ログインしていない人には返さない
// (上の REST API の制限を外した場合の備え)
add_filter( 'rest_endpoints', function ( $endpoints ) {
if ( ! is_user_logged_in() ) {
unset( $endpoints['/wp/v2/users'], $endpoints['/wp/v2/users/(?P<id>[\d]+)'] );
}
return $endpoints;
} );
// RSS フィードの著者名(<dc:creator>)は、表示名の代わりにサイト名を出す
add_filter( 'the_author', function ( $author ) {
return is_feed() ? get_bloginfo( 'name' ) : $author;
} );
// oEmbed(記事の埋め込み)の著者名・著者ページの URL を返さない
// (上の REST API の制限を外した場合の備え)
add_filter( 'oembed_response_data', function ( $data ) {
unset( $data['author_name'], $data['author_url'] );
return $data;
} );
// ログイン失敗時のメッセージを共通にして、ユーザー名が正しいかを分からなくする
add_filter( 'login_errors', function () {
return 'ユーザー名またはパスワードが正しくありません。';
} );
wp-content/mu-plugins/sitemap-exclude.php
<?php
/**
* サイトマップから、ユーザー(投稿者)の一覧を外す
* 投稿者のページのURLには、ログインのユーザー名が含まれるため
*/
add_filter( 'wp_sitemaps_add_provider', function ( $provider, $name ) {
return ( 'users' === $name ) ? false : $provider;
}, 10, 2 );
/**
* サイトマップから、特定の固定ページだけを外す
* 外したいページは、$exclude_slugs にスラッグ(URLの最後の部分)を追加する
*/
add_filter( 'wp_sitemaps_posts_query_args', function ( $args, $post_type ) {
if ( 'page' !== $post_type ) {
return $args;
}
$exclude_slugs = array(
'test',
);
$ids = array();
foreach ( $exclude_slugs as $slug ) {
$page = get_page_by_path( $slug );
if ( $page ) {
$ids[] = $page->ID;
}
}
$args['post__not_in'] = array_merge( $args['post__not_in'] ?? array(), $ids );
return $args;
}, 10, 2 );
Nginx Cache Controller
wp-content/mu-plugins/nginx-cache-controller-https.php
<?php
if ( class_exists( 'NginxChampuru' ) ) {
add_filter( 'nginxchampuru_flush_cache', function ( $url ) {
global $wpdb;
$nginxchampuru = NginxChampuru::get_instance();
$table = "{$wpdb->prefix}nginxchampuru";
$keys = $wpdb->get_col( $wpdb->prepare(
"SELECT `cache_key` FROM `{$table}` WHERE `cache_url` = %s",
$url
) );
if ( empty( $keys ) ) {
return;
}
foreach ( $nginxchampuru->get_cache_file( $keys ) as $cache ) {
if ( is_file( $cache ) ) {
@unlink( $cache );
}
}
$placeholders = implode( ',', array_fill( 0, count( $keys ), '%s' ) );
$wpdb->query( $wpdb->prepare(
"DELETE FROM `{$table}` WHERE `cache_key` IN ({$placeholders})",
$keys
) );
}, 10, 1 );
add_filter( 'nginxchampuru_get_cache', function ( $key, $url = null ) {
$nginxchampuru = NginxChampuru::get_instance();
if ( ! $url ) {
$url = $nginxchampuru->get_the_url();
}
$keys = array( $key );
if ( $key !== $nginxchampuru->get_cache_key( $url ) ) {
$keys[] = $nginxchampuru->get_cache_key( $url );
}
return $nginxchampuru->get_cache_file( $keys );
}, 10, 2 );
}
/**
* キャッシュ作成時刻を日本時間で出力(X-Cached の日本時間版)
*/
add_action( 'send_headers', function () {
if ( is_admin() ) {
return;
}
$now = new DateTime( 'now', new DateTimeZone( 'Asia/Tokyo' ) );
header( 'X-Cached-JST: ' . $now->format( 'Y-m-d H:i:s T' ) );
} );
BASIC認証
dnf install -y httpd-tools
BA_USER="admin"
BA_PASS=$(openssl rand -base64 32 | tr -d '/+=' | cut -c1-16)
htpasswd -bcB /etc/nginx/.htpasswd "${BA_USER}" "${BA_PASS}"
chown root:nginx /etc/nginx/.htpasswd
chmod 640 /etc/nginx/.htpasswd
echo "ユーザー: ${BA_USER}"
echo "パスワード: ${BA_PASS}"
unset BA_PASS
#サイト全体にかける場合
server {
...
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
...
}
#特定のパスだけにかける場合
location /admin/ {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
#Let's Encrypt
location = /.well-known/acme-challenge/ {
auth_basic off;
}
nginx -t
systemctl reload nginx