mohisham mohisham - 3 months ago 28x
Linux Question

Tomcat/Angular app on Windows vs Linux and trailing slash

I have an issue which I'm not sure is related to angular or my server (tomcat 7).

I have so far been developing on my local machine which is a Windows box, and I have been able to deploy and run my webapp successfully so far with no issues. I access the site by going to the URL: http://localhost:8080/appname

Now the $stateProvider for my angular app correctly loads the default state (so that the URL becomes http://localhost:8080/appname/#/login).

I now deployed to our test environment which is a linux machine (same tomcat7). When I now go the URL: http://test-box:8080/appname
it goes to this instead: http://test-box:8080/appname#/

Notice the missing trailing slash after "appname". Only a blank page gets loaded. I don't know where the problem may be, tomcat or angular, though I'm leaning towards the latter.


So I never managed to figure out why this was only happening on my test environment, but I did manage to get around the problem. I did the following:

  1. Enabled html5 mode for the angular app:

        enabled: true,
        requireBase: true

    I have requireBase as 'true' because as I mentioned above, the webapp has an appName, which leads me to point 2.

  2. To make sure your angular app can work with your base app name, add this to your main index.html file:

    <base href="/appName/">

    Make sure this is done at the top in the <head> tag

  3. The above fixed my problem, but introduced a new one. Because of the html5 mode, you will no longer see a # in your URL. And now when you refresh the page, because the URL is now managed completely by angular, the server may not know how to handle the resource you are trying to access. It may not even exist on the server-side and you will get a 404. So, if you refresh the page and try to access anything which the server does not know about (in my case, anything starting with appName/api, appName/resourc, etc. are ok) it should be redirected to index.html. This means that you will need to rewrite your URL's. Unfortunately, tomcat7 does not support this, so I had to upgrade to tomcat8. URL rewriting can also be configured on an apache front-end server. If you are able to do that, enable URL rewriting in conf/server.xml:

    <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">
        <Valve className="org.apache.catalina.valves.rewrite.RewriteValve" />

    Then create a new file called conf/rewrite.config which has:

    RewriteCond %{REQUEST_URI} ^/appName/(api|resource).*$
    RewriteRule ^.*$ - [L]
    RewriteRule ^.*$ /appName/index.html [L,QSA]

    This says that anything starting with api/* or resource/* is OK, everything else must be redirected to index.html.