Search code examples
angular.htaccessangular-ui-routerapache2hash-location-strategy

Angular 13 app deployed on apache server throwing 404 Error on refresh


I have created one prototype web app and need to deploy on apache server on ubuntu OS. I have build my web app and hosted on local machine to run for testing. I have enabled setup the .htaccess with,

RewriteEngine on

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]  
RewriteCond %{REQUEST_FILENAME} -d  
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

Now, my screen url is look like, http://localhost/PROJECT-NAME/user/31/case/99 such URL is being redirected from another link available in index.php and once the angular page loads, everything is fine, the moment i refresh the browser, it throws me a 404 Error

available environment is,

Angular CLI: 13.3.3
Node: 14.17.4
Package Manager: npm 8.7.0
OS: linux x64

Angular: 
... 

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.1303.3 (cli-only)
@angular-devkit/core         13.3.3 (cli-only)
@angular-devkit/schematics   13.3.3 (cli-only)
@schematics/angular          13.3.3 (cli-only)

could one will help me here, I tried all sorts of .htaccess and technique so far..

let me know if one require more inputs here, would appreciate your help.


Solution

  • The described issue sounds like you do not use correct rewrite rules and the Apache is unable to handle the request properly. That's why the pretty URLs do not work if you try to access them directly. ( It's normal for the URLs to work when you navigate the sub-pages through the home page as it is most probably a SPA ). Please try using the following rewrite rules in your .htaccess file:

    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]