I want to deploy an Angular 2 application on an Apache server. I\'ve read various guides like this and this but none of them is working. I have npm
and ng
For Apache, to redirect any request to index.html, you need a .htaccess file in the root. Just create a .htaccess in your dist folder (same level as index.html), I assume that's the public root of your app, and paste this in the .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# not rewrite css, js and images
RewriteCond %{REQUEST_URI} !\.(?:css|js|map|jpe?g|gif|png)$ [NC]
RewriteRule ^(.*)$ /index.html?path=$1 [NC,L,QSA]
Now, no matter what path you're requesting, Apache will always serve your index.html file, except requests to actual existing files (RewriteCond %{REQUEST_FILENAME} !-f) and requests to css, js etc. (RewriteCond %{REQUEST_URI} !.(?:css|js|map|jpe?g|gif|png)$) - which needed to be excluded, because you actually want those. Also, the Apache's mod_rewrite extension needs to be enabled for this to work. Most often, it is enabled. If not, ask your hosting provider
It appears i was missing this in my /etc/apache2/sites-enabled/000-default.conf
file. After adding this and restarting apache
, website runs fine.
<Directory "/var/www/html/dist">
AllowOverride All
</Directory>
Change base tag in index.html file
<base href="./">
Create a build after that
ng build --prod
Now you will have a new folder dist, deploy dist folder now. It should work.
Change base tag in index.html file
Run:
ng build --prod -bh "http://example.net"
Create .htaccess
file in the root folder and paste this in .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
open your index.html in dist directory after
ng build --prod
and Chang base element to your site DNS name for example for my local apache server I changed from
<base href="/">
to
<base href="//localhost/angular2/ng2-cli/dist/">