Ravindra BagaleCourses & study guides

Chapter 7: Static Website Hosting (3 OSes × 2 Web Servers)

7.10 Combination 5 — CentOS Stream 9 + Nginx

sudo yum install -y nginx
sudo service nginx start
sudo systemctl enable nginx

sudo tee /etc/nginx/conf.d/mysite.conf > /dev/null <<'EOF'
server {
    listen 80;
    listen [::]:80;
    server_name YOUR_SERVER_NAME;
    root /var/www/mysite;
    index index.html;
    location / {
        try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
}
EOF
sudo sed -i "s/YOUR_SERVER_NAME/$(curl -s https://checkip.amazonaws.com)/" /etc/nginx/conf.d/mysite.conf

# SELinux: give the files the web-content label
sudo restorecon -Rv /var/www/mysite
ls -Z /var/www/mysite            # should show httpd_sys_content_t

# firewalld: only if it is active
if systemctl is-active --quiet firewalld; then
  sudo firewall-cmd --permanent --add-service=http --add-service=https
  sudo firewall-cmd --reload
fi

sudo nginx -t && sudo service nginx reload
curl -s http://localhost -H "Host: $(curl -s https://checkip.amazonaws.com)" | head -5

SELinux and custom folders

/var/www/... automatically gets the correct label, but a folder elsewhere (e.g. /data/site or /home/ec2-user/site) does not. For such folders add a rule, then relabel: sudo semanage fcontext -a -t httpd_sys_content_t "/data/site(/.*)?" and sudo restorecon -Rv /data/site (the semanage command comes from package policycoreutils-python-utils). Files moved with mv keep their old label — always run restorecon after moving.