angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

404 when manually changing URL in browser to defined router route

Open brookhutchinson opened this issue 9 years ago • 86 comments

OS?

Windows 10

Versions

[email protected]

Background

Angular App was created using angular-cli. Angular App contains a NavbarComponent that displays two menu items "Home" and "About". Angular App uses the Angular Router and a NavbarComponent to allow the user to navigate to two component views: HomeComponent View and AboutComponent View. The base route for the app is set inside index.html as . A Router Configuration File is defined and defines two routes, one route as the HomeComponent default route with a path: '' and one route as the AboutComponent Path with a path: 'about'. The ConfiguredRouterModule is exported from app.routing.ts The ConfiguredRouterModule is imported into app.module.ts. A directive is defined inside the AppComponent HTML Template. A routerLink directive is defined for each menu item link inside the NavbarComponent. To build the project I use the angular-cli command "ng build --prod". I copy files from "dist" folder to destination web server folder. Note that the destination web server folder is a sub folder under the root folder on the web server. Example "root/projects/router" and not just the "root" folder

NavbarComponent Menu Item Links correctly render Component Views

When a user clicks on either or the NavbarComponent menu item links "Home" or "About" the correct Component View displays inside the inside the AppComponent HTML Template

Issue

When a user manually changes the URL in the browser from "http://www.abc.com/projects/router/" to "http://www.abc.com/projects/router/about" instead of the AboutComponent displaying, a 404 Page Not Found Error is displayed. Note that this behavior does not produce a 404 Page Not Found Error when running the ng serve command in the development environment. This behavior only produces a 404 Page Not Found Error when building and deploying code to a web server.

After I execute the command ng build --prod I have to change the <base href="value"> from <base href="/"> to <base href="/projects/router/">.

Note that if I try to build the project using the angular-cli command ng build --prod --base-href projects/router, after executing command if I open the index.html file inside the "dist" folder I see that angular-cli changed the <base href="value"> from <base href="/" to <base href="C:/Program Files/Git/projects/router/>

My Questions

How do I build the Angular Project so that the <base href="value"> is set correctly? More importantly why is the Angular App giving a 404 Error if a user manually changes the URL in the browser to a valid router route path? Example http://www.abc.com/projects/router/about"

brookhutchinson avatar Feb 28 '17 16:02 brookhutchinson

Read the thread, do the figuring out. Every week someone on here asks practically the same question. Just read it mate.

DavTho1983 avatar Dec 18 '17 14:12 DavTho1983

@DavTho1983 , I have fixed it by my own. Thanks :)

Jithesh-Menon avatar Dec 18 '17 18:12 Jithesh-Menon

Jithesh - I'm facing the same issue. Could you share your solution? Really appreciate your help.

Johnnyraj avatar Dec 27 '17 20:12 Johnnyraj

Jithesh - I have fixed the issue using following link.. https://groups.google.com/forum/#!topic/angular/JqhmL6ocPDY

Thanks you..

Johnnyraj avatar Dec 27 '17 20:12 Johnnyraj

DON'T USE REWRITE IN WEB.CONFIG as this will will redirect to a point and again it will try to execute some piece of code that actually not required. This will hamper the IIS i have tested by checking the event logs in the server. use useHash location strategy instead.

sharathgg5 avatar Jan 22 '18 14:01 sharathgg5

If Apache is web server then make .htaccess file and paste the below:

RewriteEngine On # If an existing asset or directory is requested go to it as it is RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] # If the requested resource doesn't exist, use index.html RewriteRule ^ /sub-folder-name/index.html

salmanyaqoobin avatar Feb 07 '18 14:02 salmanyaqoobin

After All this, if you haven't tried lite-server please try it first !!

pratik97 avatar Feb 08 '18 13:02 pratik97

@uviekelvin I managed to use a rewrite rule to send the index.html file but once the page reaches the client, how does the app "knows" what was the route that was requested originally? At first, I thought you were sending some special header for that but I don't see one. can you explain that part, please?

kramer888 avatar Feb 10 '18 22:02 kramer888

@brookhutchinson , I had the same problem

  1. run ng build --prod
  2. dist folder will be created, paste the following .htaccess file inside
  3. upload to your server (in my case shared hosting)

Add .htaccess in your root folder, same level with your index.html with this HTACCESS content


RewriteEngine On  
  # If an existing asset or directory is requested go to it as it is
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^ - [L]

  # If the requested resource doesn't exist, use index.html
  RewriteRule ^ /index.html

sanchezbroz avatar Feb 13 '18 09:02 sanchezbroz

screen shot 2018-02-19 at 1 20 43 am I've deployed my angular 5 project on aws s3 bucket and i am getting this '403 Forbidden error' if I referesh the page on a routed component(awsbucketurl/books), I don't wanna use HashLocationStrategy, please help me out here.

gaurav-pantelwar avatar Feb 18 '18 19:02 gaurav-pantelwar

Use this with HTTPS Websites

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

For HTTP Websites

RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html


sushinpv avatar Feb 27 '18 03:02 sushinpv

I'm having the same problem but only with lazy loading modules. When I hit a route that is not part of a lazy loading module it loads, but when I try for lazy loading modules Apache throws a 404 error.

In my local environment, it works great for all routes.

All this is happening to me after upgrading to Angular 5 and ng cli 1.6.8.

juanhenriquez avatar Mar 07 '18 01:03 juanhenriquez

I wanted to show the 404.html for the wrong URLs. So, { path: '**', component: PageNotFoundComponent } I have tried with above thing abut it was not working properly.

Then I have used below code, and it's working fine. Woeking code 👍

PageNotFoundComponent Route:

{ path: '404', component: PageNotFoundComponent }

export class AppRoutingModule {
constructor(private router: Router) {
	this.router.errorHandler = (error: any) => {
		let routerError = error.toString();
            if (routerError.indexOf('Cannot match any routes') >= 0 ) {
                this.router.navigate(['/404']);
            } else {
                throw error;
            }
	}
  }
}

Thanks to @mejayantpatil

vishalbiradar avatar Mar 10 '18 08:03 vishalbiradar

This tutorial may help you

http://amypeniston.com/web/htaccess-angular-hash-routing

flavio-araujo avatar Apr 18 '18 14:04 flavio-araujo

I ended up using lite-server. It automatically serves /index.html on any 'unknown' route. I hope I can save you guys some time of searching, because, jekyll (GitHub), apache (local Windows), http-server have been beasts to me while solving this problem.

microglossum avatar Jun 01 '18 17:06 microglossum

For those who use the Firebase Hosting as web server to host a Angular application. You should check this link firebase hosting redirect.

As mentioned you have to add those lines of code in your firebase.json

"hosting": {
  // Add the "rewrites" section within "hosting"
  "rewrites": [ {
    "source": "**",
    "destination": "/index.html"
  } ]
}

It just save my day, so I share.

olivejp avatar Jul 03 '18 21:07 olivejp

@all ng build --base-href="/TEST/"

ng server --base-href="/NIHB/"

This will help to solve this error

shrisowdhaman avatar Jul 27 '18 17:07 shrisowdhaman

If you are deploying your angular app on JBOSS/Apache as war file, then add following in your web.xml file:-

<error-page>
        <error-code>404</error-code>
        <location>/index.html</location>
</error-page>

This will redirect to index.html of your angular app in case of 404 not found error which then renders the required route and view. (It works even if you are manually trying to go to a correct route.)

vaishalichawla26 avatar Jul 31 '18 09:07 vaishalichawla26

Does anyone know how to use the useHash solution with Angular 6 while using a appRoutingModule file for their routes?

sabeehshah avatar Aug 04 '18 01:08 sabeehshah

use inside into tag. Note it should be top inside head tag.

other css and jquery ...

sonu2010 avatar Aug 23 '18 14:08 sonu2010