Ubuntu 20.04 Nginx Let’sEncrypt でHTTPSサイト作成

Nginx インストール

アップデート
sudo apt update

nginx インストール
sudo apt install nginx

ステータス確認
sudo systemctl status nginx

設定再読み込み
sudo systemctl reload nginx

自動再起動有効
sudo systemctl enable nginx

/etc/nginx/conf.d/*設定ファイル*.confを作成

Let’s Encrypt インストール

sudo apt install snapd

sudo snap install --classic certbot

sudo ln -s /snap/bin/certbot /usr/bin/certbot

certbot --version

lets encryptの初期設定
sudo certbot --nginx --key-type rsa -d ドメイン

1日2回SSLが切れてないか確認するsnap.certbot.renew.timerが実行されているか確認
systemctl list-timers

実行時間の編集
vi /etc/systemd/system/snap.certbot.renew.timer

反映
systemctl daemon-reload
systemctl restart snap.certbot.renew.timer

Nginx の公開される場所

/var/www/html

PHPインストール

sudo add-apt-repository ppa:ondrej/php

sudo apt update

sudo apt install php8.1
sudo apt install php8.1-bcmath php8.1-bz2 php8.1-curl php8.1-fpm php8.1-gd php8.1-mbstring php8.1-mysql php8.1-xml php8.1-zip
php -v


php.ini
post_max_size = 60M
upload_max_filesize = 50M

設定反映
systemctl restart php8.1-fpm

Nginx設定

Httpsで設定をしてドメイン以外のアクセスは拒否する

server {
	listen [::]:443 ssl ipv6only=on;
	listen 443 ssl;

	root /var/www/html;

	index index.html index.htm index.php;

	server_name ドメイン;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}

	# pass PHP scripts to FastCGI server
	#
	location ~ \.php$ {
		include snippets/fastcgi-php.conf;

		# With php-fpm (or other unix sockets):
		fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
	}

	# deny access to .htaccess files, if Apache's document root
	# concurs with nginx's one
	#
	location ~ /\.ht {
		deny all;
	}
	ssl_certificate /etc/letsencrypt/live/ドメイン/fullchain.pem;
	ssl_certificate_key /etc/letsencrypt/live/ドメイン/privkey.pem;
	include /etc/letsencrypt/options-ssl-nginx.conf;
	ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;


}
server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
 
    server_name _;

	ssl_certificate /etc/letsencrypt/live/ドメイン/fullchain.pem;
	ssl_certificate_key /etc/letsencrypt/live/ドメイン/privkey.pem;
	include /etc/letsencrypt/options-ssl-nginx.conf;
	ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
 
    return 404;
}

PHPテストコード

index.php
<!DOCTYPE html>
<html>
    <head>
        <title>PHP Test</title>
    </head>
    <body>
        <?php echo '<p>Hello World</p>'; ?>
    </body>
</html>