How to configure apache for angular 2

2020-02-26 01:58发布

问题:

I need to configure virtual host for angular2. I have tried following this article

https://www.packtpub.com/mapt/book/Web+Development/9781783983582/2/ch02lvl1sec15/Configuring+Apache+for+Angular

According to this i need to setup virtual host like this

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        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]
    </Directory>
</VirtualHost>

Can anyone tell me what should be the path to app as my app is running on default angular 2 port that is 4200. Is there any other way to do it.

回答1:

angular-cli build

On your local development environment run ng build --prod in your project root.

This will create a folder called dist, you want to place all the files and folders from within dist to your Apache root directory on your server.

Setup apache to serve routes to index.html. You have two methods you can use, either edit your virtual host or use .htaccess in your website root directory.


Option 1: Virtual Host

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        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]
    </Directory>
</VirtualHost>

Option 2: .htaccess

<IfModule mod_rewrite.c>
    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]
</IfModule>