Search code examples
angular.htaccessurlapache2

How to configure routing on Angular app with DNS pointing to my VPS?


I have a domain mydomain.example which point to my VPS Ubuntu Apache web server. On my VPS I have angular app.

If I go to http://mydomain.example it shows the content from /home and the browser URL remains http://mydomain.example, this is OK and it works. However, if I refresh a page with reload() method or refresh button on browser I get an error:

no page http://mydomain.example/home.

How to do this in single page app? Does .htaccess help?

Clicking links in my app works. Reload does not work. I think it is because it uses mydomain + angularComponet and not my index.html/angularComponent.


Solution

  • Reload/refresh does not work because you are sending a new HTTP request to your (Apache) server and your server does not know how to respond. When you click the links in your application JS/Angular captures the event and routes the request through your Angular front-controller - which all happens client-side (no direct HTTP request to the server, except for those that might be initiated through Angular).

    You need to implement a server-side front-controller pattern so that any "unknown" HTTP requests to your server are also routed through the Angular front-controller.

    On Apache, you can do something like the following in the root .htaccess file (or server config). This uses mod_rewrite.

    DirectoryIndex index.html
    
    RewriteEngine on
    
    # Angular front-controller
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.html [L]
    

    This is a standard front-controller pattern that routes all requests that don't map to files or directories to the file index.html (the Angular front-controller) that should then handle the request.

    You need to make sure that .htaccess overrides are enabled in the server config (AllowOverride All needs to be set in the appropriate place eg. <Directory> container inside the relevant <VirtualHost>, and Apache restarted). You also need to make sure that mod_rewrite is installed/enabled, otherwise this will generate a "500 Internal Server Error" (in which case check your server's error log for details).