Ravindra BagaleCourses & study guides

Chapter 8: Configuring Nginx and Apache

8.3 Task: change the Nginx document root

Suppose the website must be served from /var/www/portfolio instead of the default folder.

# 1. create the folder and a test page
sudo mkdir -p /var/www/portfolio
echo '<h1>Portfolio served from /var/www/portfolio</h1>' | sudo tee /var/www/portfolio/index.html
sudo chmod 755 /var/www/portfolio
sudo chmod 644 /var/www/portfolio/index.html

Amazon Linux 2023 / CentOS Stream 9: create a site file (the built-in block inside nginx.conf still exists, so we check which block is the default):

sudo tee /etc/nginx/conf.d/portfolio.conf > /dev/null <<'__EOCONF__'
server {
    listen 80;
    listen [::]:80;
    server_name _;
    root /var/www/portfolio;
    index index.html;
    location / { try_files $uri $uri/ =404; }
}
__EOCONF__
grep -n "default_server" /etc/nginx/nginx.conf      # if found, remove "default_server" there
sudo nginx -t && sudo service nginx reload

Why grep for default_server?

In /etc/nginx/nginx.conf the line include /etc/nginx/conf.d/*.conf; comes before the built-in server { ... } block. So if no block says default_server, your conf.d block loads first and wins for unknown names. But some package versions mark the built-in block listen 80 default_server;, and then it wins instead. The fix is either to put your real domain or public IP in server_name (as in Chapter 7), or to move default_server to your own block.

Ubuntu: edit the site file and change one line:

sudo sed -i 's#root /var/www/html;#root /var/www/portfolio;#' /etc/nginx/sites-available/default
grep -n "root" /etc/nginx/sites-available/default
sudo nginx -t && sudo service nginx reload

CentOS Stream 9 only: SELinux. Folders under /var/www automatically get the correct httpd_sys_content_t label. For any other path, such as /srv/portfolio or /data/site, you must teach SELinux about it, or you'll get 403 Forbidden:

sudo yum install -y policycoreutils-python-utils           # provides semanage
sudo semanage fcontext -a -t httpd_sys_content_t "/srv/portfolio(/.*)?"
sudo restorecon -Rv /srv/portfolio
ls -Z /srv/portfolio                                        # should show httpd_sys_content_t

Verify with curl -s http://localhost | head -3 and then from your browser.

Never point the root at /root or /home/ec2-user

The web server runs as nginx / www-data / apache, which can't read inside home folders (permissions 700/750). Changing folder permissions on your home to "fix" a 403 exposes your SSH keys and files. Keep websites under /var/www (or /srv) and copy files there.