Deploy Angular 2 to Apache Server

后端 未结 8 1961
半阙折子戏
半阙折子戏 2020-12-07 16:47

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

相关标签:
8条回答
  • 2020-12-07 17:30

    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

    0 讨论(0)
  • 2020-12-07 17:31

    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>
    
    0 讨论(0)
  • 2020-12-07 17:31
    1. Change base tag in index.html file

      <base href="./">

    2. Create a build after that

      ng build --prod

    3. Now you will have a new folder dist, deploy dist folder now. It should work.

    0 讨论(0)
  • 2020-12-07 17:31

    Change base tag in index.html file

    Run:

    ng build --prod -bh "http://example.net"
    
    0 讨论(0)
  • 2020-12-07 17:36

    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>
    
    0 讨论(0)
  • 2020-12-07 17:43

    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/">
    
    0 讨论(0)
提交回复
热议问题