Essential Terminal Commands to Secure an Apache Website on Ubuntu

This guide provides essential terminal commands to secure websites (e.g., Laravel, WordPress applications) on an Ubuntu server running Apache, tailored for beginners new to VPS or Linux. It covers setting correct file permissions, configuring UFW (Uncomplicated Firewall), and implementing additional security measures to protect the server. Securing a website and server on Ubuntu, especially if you’re managing your own VPS, is critical.


1. Set Correct File Permissions for Websites

Proper file permissions prevent unauthorized access or modifications. For a Laravel-based website or WordPress, the web server user (www-data for Apache on Ubuntu) needs appropriate ownership and permissions.

123456789101112131415
sudo chown -R www-data:www-data /var/www/html/your_website

# Files: Read/write for owner, read-only for group/others
sudo find /var/www/html/your_website -type f -exec chmod 644 {} ;

# Directories: Read/write/execute for owner, read/execute for group/others
sudo find /var/www/html/your_website -type d -exec chmod 755 {} ;

# Laravel specific
sudo chmod -R 775 /var/www/html/your_website/storage
sudo chmod -R 775 /var/www/html/your_website/bootstrap/cache

# WordPress specific
sudo chmod -R 775 /var/www/html/your_website/wp-content/uploads
sudo chmod -R 775 /var/www/html/your_website/wp-content/cache
  • www-data is the default Apache user on Ubuntu, needing ownership to serve files.
  • 644 for files ensures only the owner (Apache) can write, while others can read.
  • 755 for directories allows Apache to access and execute, but not write unnecessarily.
  • Laravel’s storage and bootstrap/cache need write permissions for logs and caching.
  • WordPress requires write permissions in wp-content/uploads & cache folder.

2. Secure the Server with UFW (Uncomplicated Firewall)

UFW is a beginner-friendly firewall tool to control incoming and outgoing traffic. Always allow SSH (port 22) before enabling UFW to avoid locking yourself out.

1234567891011121314151617181920212223242526
#To check if UFW (Uncomplicated Firewall) is installed on your system, run this command in your terminal:
# If UFW is installed, you'll see something like: /usr/sbin/ufw
which ufw
#or you can also do 
ufw --version

# Install UFW if not already installed
sudo apt update
sudo apt install ufw

# Allow essential services (SSH, HTTP, HTTPS)
sudo ufw allow 22/tcp    # SSH for remote access
sudo ufw allow 80/tcp    # HTTP for websites
sudo ufw allow 443/tcp   # HTTPS for secure websites

# Deny all other incoming traffic by default
sudo ufw default deny incoming

# Allow all outgoing traffic (safe for most setups)
sudo ufw default allow outgoing

# Enable UFW
sudo ufw enable

# Check UFW status
sudo ufw status
  • UFW restricts access to only necessary ports (e.g., 22 for SSH, 80/443 for web traffic).
  • Always allow SSH (port 22) before enabling UFW to avoid locking yourself out.
  • Denying incoming traffic by default reduces attack surfaces.

3. Secure SSH Access

SSH is often targeted by attackers, so securing it is critical.

1234567891011121314151617181920
# Edit SSH configuration
sudo nano /etc/ssh/sshd_config

# Change the default SSH port (e.g., from 22 to 2222 for obscurity)
Port 2222

# Disable root login
PermitRootLogin no

# Allow only specific users (replace 'your_username' with your actual user)
AllowUsers your_username

# Save and exit (Ctrl+O, Enter, Ctrl+X in nano)

# Restart SSH service
sudo systemctl restart sshd

# Update UFW to allow the new SSH port (if changed)
sudo ufw allow 2222/tcp
sudo ufw deny 22/tcp
  • Changing the SSH port reduces automated bot attacks targeting port 22.
  • Disabling root login prevents brute-force attacks on the root account.
  • Restricting users ensures only authorized accounts can SSH.

4. Secure Apache Configuration

Apache needs to be configured to minimize vulnerabilities.

1234567891011121314151617181920212223242526272829303132333435
# Edit Apache's main configuration file
sudo nano /etc/apache2/apache2.conf

# Add or ensure the following settings
<Directory /var/www/html>
    Options -Indexes    # Disable directory listing
    AllowOverride All   # Allow .htaccess for additional security
</Directory>

# Save and exit

# Disable unnecessary Apache modules
sudo a2dismod status    # Disable server status page
sudo a2dismod autoindex # Disable directory indexing

# Enable security modules
sudo a2enmod headers
sudo a2enmod rewrite

# Add security headers to your site’s configuration
sudo nano /etc/apache2/sites-available/your_website.conf
# Add inside <VirtualHost>:
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "DENY"
    Header set X-XSS-Protection "1; mode=block"
</IfModule>

# Save and exit

# Test Apache configuration
sudo apache2ctl configtest

# Restart Apache
sudo systemctl restart apache2
  • Disabling directory listing (-Indexes) prevents attackers from seeing file structures.
  • Security headers protect against common attacks like XSS and clickjacking.
  • Disabling unused modules reduces potential vulnerabilities.

5. Install and Configure SSL/TLS with Let’s Encrypt

Securing your website with HTTPS ensures that all data exchanged between your server and visitors is encrypted and protected from tampering.
There are a few ways to set this up:

  • Cloudflare and similar services offer free SSL/TLS with easy DNS-level integration — great for beginners or if you want quick protection.
  • If you prefer to manage your own SSL certificates directly on the server, Let’s Encrypt is a solid free option.
  • You can also purchase paid SSL certificates if you need extended validation (EV), warranties, or wildcard/multi-domain support.
    Here’s how to set up Let’s Encrypt with Certbot on Apache:
12345678910
# Install Certbot and the Apache plugin
sudo apt update
sudo apt install certbot python3-certbot-apache

# Obtain and install an SSL certificate
sudo certbot --apache -d yourdomain.com -d www.yourdomain.com

# Enable automatic certificate renewal
sudo systemctl enable certbot.timer
sudo systemctl start certbot.timer
  • HTTPS encrypts data between the server and users, preventing eavesdropping.
  • Let’s Encrypt provides free SSL certificates, and Certbot automates setup/renewal.

6. Keep the System Updated

Regular updates patch security vulnerabilities.

123456
# Update package lists and upgrade installed packages
sudo apt update && sudo apt upgrade -y

# Enable automatic security updates
sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades
  • Outdated software is a common entry point for attacks.
  • unattended-upgrades automates security patches.

7. Secure the Server with Basic User Management

Avoid using the root account and create a non-root user with sudo privileges.

12345678
# Create a new user
sudo adduser your_username

# Add user to sudo group
sudo usermod -aG sudo your_username

# Log in as the new user
su - your_username
  • Using a non-root user reduces the risk of catastrophic changes if compromised.

8. Monitor and Log Suspicious Activity

Install tools to monitor server activity.

12345678
# Install and configure fail2ban to block brute-force attacks
sudo apt install fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban

# Check logs for suspicious activity
sudo tail -f /var/log/auth.log
sudo tail -f /var/log/apache2/access.log
  • fail2ban bans IPs after repeated failed login attempts.
  • Monitoring logs helps detect unauthorized access early.

9. Backup Your Website

Regular backups ensure you can recover from attacks or failures.

1234567
# Create a backup of your website
sudo tar -czf /backups/website_backup_HX$(date +%F).tar.gz /var/www/html/your_website

# Automate backups with a cron job
sudo crontab -e
# Add (backs up daily at 2 AM):
0 2 * * * tar -czf /backups/website_backup_$(date +%F).tar.gz /var/www/html/your_website
  • Backups allow quick restoration after data loss or ransomware.

10. Additional Tips for Beginners

  • Use strong passwords: Generate and store complex passwords with a password manager.
  • Disable unused services: Check running services with sudo netstat -tulnp and stop unnecessary ones.
  • Learn basic commands: Familiarize yourself with ls, cd, nano, systemctl, and journalctl.
  • Test changes: Always test configurations (e.g., apache2ctl configtest) before restarting services.
  • Use a VPS provider’s firewall: Many VPS providers (e.g., DigitalOcean, AWS) offer additional firewalls—use them alongside UFW.

Notes

  • Replace /var/www/html/your_website with your actual website directory.
  • Replace yourdomain.com with your domain.
  • Always back up configurations before editing.
  • If locked out (e.g., SSH or UFW issues), use your VPS provider’s console access to recover.

This guide provides a solid foundation for securing your Ubuntu server and Apache-hosted websites. For further assistance, consult your VPS provider’s documentation or community forums.