Nginx + let’s encriptで “virtualhost + 80->443 redirect”

161

マストドンサーバの構築準備にともない、初めて nginxを触ってみたので基礎部分だけメモ。

以下のようなものを /etc/nginx/site-{available/enabled}/ に複数置くだけで、sslサイトへの自動リダイレクトができます、やっぱり apache より簡単そうですね。Let’s encriptも全く問題は発生せず。


server {
        root /html/mastodon/;

        index index.html index.php index.htm index.nginx-debian.html;
        server_name mastodon.zenmai.org; # managed by Certbot

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

location ~.php$ {
                include snippets/fastcgi-php.conf;

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

    listen [::]:443 ssl ipv6only=on; 
    listen 443 ssl; 
    ssl_certificate /etc/letsencrypt/live/mastodon.zenmai.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mastodon.zenmai.org/privkey.pem; 
    include /etc/letsencrypt/options-ssl-nginx.conf; 
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

}


server {

    if ($host = mastodon.zenmai.org) {
        return 301 https://$host$request_uri;
    }
        
        listen 80 ;
        listen [::]:80 ;
        server_name mastodon.zenmai.org;
        return 404;
}