Ravindra BagaleCourses & study guides

Chapter 8: Configuring Nginx and Apache

8.8 Useful everyday configurations

Redirect www to the main domain (or the reverse)

server {
    listen 80;
    server_name www.example.com;
    return 301 http://example.com$request_uri;
}
<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / http://example.com/
</VirtualHost>

Redirect HTTP to HTTPS

Certbot adds this automatically. By hand, it's return 301 https://$host$request_uri; (Nginx) or Redirect permanent / https://example.com/ (Apache) in the port-80 block.

Hide version numbers

# Nginx: inside http { } of nginx.conf
server_tokens off;
# Apache (AL2023/CentOS): new file /etc/httpd/conf.d/security.conf
ServerTokens Prod
ServerSignature Off
# Apache (Ubuntu): edit /etc/apache2/conf-available/security.conf (already enabled)

Check with curl -I http://localhost. The Server: header should show only nginx or Apache.

Increase the upload limit

client_max_body_size 20M; (Nginx, in http or server). For PHP apps, also raise upload_max_filesize and post_max_size in php.ini.

Password-protect a folder (basic auth)

sudo yum install -y httpd-tools            # Ubuntu: sudo apt install -y apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd admin
location /admin/ {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

(Apache equivalent inside <Directory>: AuthType Basic, AuthName "Restricted", AuthUserFile /etc/httpd/.htpasswd, Require valid-user.) Use this only together with HTTPS, because basic auth passwords are only base64-encoded.

Enable compression

# Nginx, inside http { }
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;

Apache: sudo a2enmod deflate on Ubuntu. On AL2023/CentOS, mod_deflate is loaded by default, so just add AddOutputFilterByType DEFLATE text/html text/css application/javascript.