Mo J. Mughrabi
Mo J. Mughrabi

Reputation: 6997

hosting angularjs app on AWS S3 storage

We are trying to host our angularjs app on S3 storage, app seem to render correctly without any errors when deployed. The angular app we use, runs with html5mode enabled for clean URLS.

We added following rule to s3 storage

<RoutingRules>
    <RoutingRule>
        <Condition>
            <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
        </Condition>
        <Redirect>
            <HostName>example.com</HostName>
            <ReplaceKeyPrefixWith>#/</ReplaceKeyPrefixWith>
        </Redirect>
    </RoutingRule>
</RoutingRules>

The problem we facing though is strange, when visiting landing page it works fine, when clicking on any links it takes you to the correct destination. But, when refresh any path url, it returns 404

I tried to update .htaccess based on several recommendations I read online. Added following

Options +FollowSymLinks

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteRule (.*) index.html [L]
    RewriteRule ^(.*)       /index.html/#/$1
</IfModule>

Please advise?

Upvotes: 2

Views: 1552

Answers (1)

ericluwj
ericluwj

Reputation: 475

First and foremost, you are supposed to change example.com to your own domain.

Secondly, I am not sure whether you did this, but you need to set the hash prefix to ! with:

angular.module(app, [])
  .config(function($locationProvider) {
    // this line is to be placed in your app config
    $locationProvider.html5Mode(true).hashPrefix('!');  
  });

To understand how the rule works, if you try the URL http://example.com/login/, the AWS S3 file server will try to find an index file in the login folder, but since the file does not exist, it will return a 404 error.

The rule will result in AWS S3 catching the 404 error and then redirecting the request to http://example.com/#!login/. Now, the AWS S3 file server will try looking for an index file in the root directory instead, because the file server naturally ignores the hash part, so it only understands part of the URL http://example.com/. So your AngularJS app file index.html will get loaded, and AngularJS will resolve the URL and load properly.

The .htaccess file is actually not related here and does nothing, because when you deploy onto AWS S3, you are using the AWS S3 file server, not your own server.

You can read more here: http://www.ericluwj.com/2015/11/10/angularjs-with-html5-mode-on-s3.html

Upvotes: 1

Related Questions