How to Solve Angular App Routing Issue on Linux Server with Apache

Introduction:

When deploying an Angular app on a Linux server running Apache, you may encounter an issue where accessing a direct URL results in a 404 error. However, navigating to the route through the app works fine. This can be frustrating, but fortunately, there’s a solution to resolve this problem. In this article, we’ll explore the issue and provide step-by-step instructions to fix it.

Understanding the Issue: The problem arises because the server does not recognize the Angular routes when accessed directly via a URL. To address this, we need to configure the server to rewrite all requests to the Angular app’s entry point, the index.html file.

Solution Steps:

For Windows

Create or Modify the .htaccess File:

  • In the root directory of your Angular app on the Linux server, create or modify the .htaccess file. This file handles server configuration and rewrite rules.
  • Add the following content to the .htaccess file:
RewriteEngine On
RewriteBase /

# If the requested file or directory does not exist,
# rewrite the URL to the index.html file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html [L]

Configure Apache to Allow .htaccess Overrides:

  • Open your Apache configuration file. The location may vary, but common paths include /etc/apache2/apache2.conf or /etc/httpd/httpd.conf.
  • Locate the <Directory> section that corresponds to your Angular app’s directory.
  • Set AllowOverride to All within the <Directory> block. This enables the server to process the .htaccess file. Here’s an example:
<Directory /path/to/your/angular/app>
    AllowOverride All
</Directory>

Restart Apache:

  • Save the changes to the Apache configuration file and exit.
  • Restart the Apache server for the new configuration to take effect. Use the appropriate command for your Linux distribution:
    • Ubuntu: sudo service apache2 restart
    • CentOS: sudo systemctl restart httpd

Test the Application:

  • Visit your Angular app by directly accessing a route URL that was previously resulting in a 404 error.
  • The app should now load correctly, without any routing issues.

Related Topics

Conclusion:

By following the steps outlined in this article, you can successfully resolve the routing issue encountered when deploying an Angular app on a Linux server running Apache. The key is configuring the server to rewrite requests to the index.html file for unrecognized routes. With this solution, your Angular app will work seamlessly, allowing users to access any route directly without encountering 404 errors.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights