How to Fix Apache Permission Denied on AWS EC2


The Root Cause This issue typically arises on AWS EC2 instances due to stricter default file system permissions or Security-Enhanced Linux (SELinux) / AppArmor enforcing restrictions. The Apache process, often running as www-data (Debian/Ubuntu) or apache (RHEL/CentOS/Amazon Linux), lacks the necessary read or execute permissions for web content directories.

Quick Fix (CLI)

# SSH into your EC2 instance and switch to root or use sudo

# 1. Adjust file ownership and permissions for your web root (e.g., /var/www/html)
#    Replace 'www-data' with 'apache' if you are on RHEL/CentOS/Amazon Linux
sudo chown -R www-data:www-data /var/www/html

# Set directory permissions to 755 (owner R/W/X, group R/X, others R/X)
sudo find /var/www/html -type d -exec chmod 755 {} \;

# Set file permissions to 644 (owner R/W, group R, others R)
sudo find /var/www/html -type f -exec chmod 644 {} \;

# 2. If SELinux is enforcing (common on RHEL/CentOS/Amazon Linux instances):
#    Verify SELinux status: getenforce
#    If 'Enforcing', apply the correct SELinux context for HTTPD content:
sudo chcon -Rt httpd_sys_content_t /var/www/html

# 3. Restart Apache to apply changes
#    Use 'apache2' for Debian/Ubuntu, 'httpd' for RHEL/CentOS/Amazon Linux
sudo systemctl restart apache2
# OR
# sudo systemctl restart httpd

Configuration Check

Verify your Apache configuration ensures the server is running as the intended user and has proper directory access rules.

  • Main Configuration File:

    • Debian/Ubuntu: /etc/apache2/apache2.conf
    • RHEL/CentOS/Amazon Linux: /etc/httpd/conf/httpd.conf
  • Changes to look for/make:

    1. User and Group Directives: Ensure Apache is configured to run as the user (www-data or apache) you set permissions for.
      # In apache2.conf or httpd.conf
      User www-data      # Change to 'apache' for RHEL/CentOS/Amazon Linux
      Group www-data     # Change to 'apache' for RHEL/CentOS/Amazon Linux
    2. Directory Access Rules: Confirm your web root directory has appropriate access directives.
      # In apache2.conf, httpd.conf, or a site-specific config file (e.g., 000-default.conf)
      <Directory /var/www/html>
          Options Indexes FollowSymLinks
          AllowOverride None          # Or All, depending on your .htaccess needs
          Require all granted         # Essential for allowing access
      </Directory>
    3. DocumentRoot: Ensure your VirtualHost or main server block’s DocumentRoot points to the correct directory (/var/www/html or your custom path).

Verification

# 1. Check Apache service status
#    Use 'apache2' for Debian/Ubuntu, 'httpd' for RHEL/CentOS/Amazon Linux
sudo systemctl status apache2
# OR
# sudo systemctl status httpd

# 2. Test connectivity from the EC2 instance itself
curl http://localhost/

# 3. Access your EC2 instance's Public IP or associated DNS in a web browser.
#    You should now see your web content without permission errors.