简体   繁体   中英

htaccess rewrite to dist folder and set AngularJS html5mode true

I have an application in AngularJS where I need to set html5mode to true in order to remove the hash /#/ from URL. The application in minified version is found in the dist folder.

QUESTION: My goal is to rewrite traffic to the dist folder and to allow the enabling of the html5mode. Can anybody help?

I can get html5mode to work by setting <base href="/" /> and adding $locationProvider.html5Mode(true); to app config and at the bottom of ui-router file.

All of this works in development mode where it's using NodeJS through Gulp. When I move the application to other environments that are on Apache, the setup has problems.

The problems are:

A. The app can't load any assets because it's looking for them in the server root.

B. The app can't reload and land on the requested URL. It gives a 404 error.

Without the html5mode enabled in the app, I am using this htaccess to redirect to dist folder and it works fine.

# This first part is not relevant for the question but is included for practical purposes. It rewrites traffic to HTTPS
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(app\.)?example\.com$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,NE,R=301]

Options +FollowSymLinks
RewriteCond %{REQUEST_URI} !(.*)dist
RewriteRule ^(.*)$ dist/$1 [L]

It needs to work the same on the difference environments so that I can use it on local as well as other environments. On local it would be on localhost/project_name/app/webapp/(dist) and in other environments it would be on https://app.example.com/(dist)

I also tried setting <base href="/dist/" /> but it also doesn't work. It only adds dist folder to the assets path and would also not be usable in development because the app is then not served from dist .

Basically the parts work but when put together it fails.

I went through many SO answers already without success:

in html5mode(true) views are not loading in page refresh in angular js

AngularJS + html5Mode + custom fallback

angularjs ngroute with html5mode(true) on apache fails

AngularJS: html5Mode(true) causing 404 error

Rather than struggling with rewrite rules, if you have Apache2, define a fallbackresource instead.

This two lines of code in the .htaccess file will solve your issue:

FallbackResource /index.php
DirectoryIndex index.html

The second line is necessary because of Google Chrome only.

To learn more about fallback resources, see the Apache documentation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM