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

How this can be fixed on NGNIX based server ?

alwinaugustin avatar Sep 05 '18 06:09 alwinaugustin

@alwinaugustin

location / {
  try_files $uri $uri/ /index.html =404;
}

grizzm0 avatar Sep 05 '18 06:09 grizzm0

None of the above .htaccess configs worked for me. Why this is closed?

kamlekar avatar Sep 19 '18 08:09 kamlekar

@kamlekar It's closed because it's not an issue with angular-cli. The issue is webserver configuration related. If none of the comments above helped you then try stackoverflow instead to get additional help.

grizzm0 avatar Sep 19 '18 08:09 grizzm0

For me none of the above .htaccess issues worked. Our admin did the following change in httpd.conf file, (in two servers) which worked:

<Directory "/var/www/html/">
    Options FollowSymLinks
    Allow from all
    AllowOverride All
</Directory>

kamlekar avatar Sep 19 '18 13:09 kamlekar

For Apache Server

  • Create a file name .htaccess
  • Edit that file and write index.html instead of index.php
  • For those who dont have any code, can write the code below in your .htaccess file :
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
  • This code might not work for SSL certificate - contact your hosting provider OR visit https://httpd.apache.org/docs/current/howto/htaccess.html to refer to docs.

smitpatelx avatar Oct 03 '18 09:10 smitpatelx

Do any one have way to fix aws s3 deployment issue highlighted by "gaurav-pantelwar commented on Feb 18 • " ?

pankajojha avatar Oct 27 '18 20:10 pankajojha

Yes @pankajojha , just make htaccess file in your main directory if you are on apache server. See above answer from @smitpatelx

smitpatelx avatar Oct 27 '18 23:10 smitpatelx

Do any one have way to fix aws s3 deployment issue highlighted by "gaurav-pantelwar commented on Feb 18 • " ?

In S3 bucket's Properties > Static web hosting try to set Error document to index.html that way non existing objects/path will be redirected to index.html

ghelobytes avatar Nov 07 '18 19:11 ghelobytes

I'm testing app using ZEIT now solution... I cannot use .htaccess not IIS solutions above.

Using hash seems great

@NgModule({
  imports: [RouterModule.forRoot(routes, {useHash: true})],
  exports: [RouterModule]
})
export class AppRoutingModule { }

But I am considering lite-server as another one sugested.

SalathielGenese avatar Nov 24 '18 12:11 SalathielGenese

Hello, i've checked the above comment carefully. Here's a problem facing now. Angular 6 production deployment into google app engine. -- app.yaml -- runtime: python27 api_version: 1 threadsafe: true handlers:

  • url: / static_files: dist/index.html upload: dist/index.html
  • url: / static_dir: dist
it works properly with entering myapp.appspot.com
but it doesn't work with 404 not found when i refresh the browser.
It would be helpful if you advice something.

CleverMobile2811 avatar Dec 06 '18 18:12 CleverMobile2811

Concerning this i used .htacees file to solve all issue 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

ah3eyy avatar Feb 10 '19 09:02 ah3eyy

For anyone still having trouble with this. I would try using angular-cli-ghpages, which will deploy your Angular app straight to Github pages with no problems. You should be able to manually go to a given route or refresh a page with no 404's.

mister-10k avatar Mar 04 '19 00:03 mister-10k

Hello Geeks, I had the same problem while Deploying angular build on IIS server, I handled this issue by adding the web.config file at the root directory of the site, with below content:

<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> </system.web> <system.webServer> <rewrite> <rules> <rule name="Rewrite Rule" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" /> </conditions> <action type="Rewrite" url="/" /> </rule> </rules> </rewrite> </system.webServer> </configuration>

Ni3-Panchal avatar Mar 22 '19 13:03 Ni3-Panchal

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

Works great. I have <base href="/"> also

nicogaldo avatar May 06 '19 13:05 nicogaldo

You likely need to configure your server to rewrite unmatched URLs to your index.html.

It worked for me with this in web.php routes file, of course in my index i have the same code from index generated in ng run build

Route::fallback(function () { return view('index'); });

anahits avatar Jul 17 '19 14:07 anahits

@sushinpv code is working for me. if i hit an url in browser it reloading the index.html rather than 404 error page in HTTP server. But I have two modules in my application one is user and another one is admin module.. when i hit my_app url it will work for user module.. if i hit my_app/admin it should render the admin page.. Now its not working, if i hit any of the url it's redirecting to index.html... its working in localhost:4200

Is there any solution for this? i'm working with Angular 7 thanks

Lavanya2021 avatar Aug 02 '19 06:08 Lavanya2021

@Lavanya2021 Hi, Which backend server you are using ?

NGINX or APACHE ??

Both required two different configuration !

  • Can you please elaborate on this point my_app/admin it should render the admin page.. Now its not working,. Like when you hit my_app/admin what output you are getting!, So that i would be able to help you out!

For reference you can checkout these pages https://lms.thegateacademy.com/ and https://lms.thegateacademy.com/dashboard/course

sushinpv avatar Aug 02 '19 07:08 sushinpv

@sushinpv Hii, I'm using APACHE server. As i said earlier,, i have 2 modules in my application, now i should make 2 urls to access the each module from the same application one for users and another one for admin. 1st is like baseurl as defined in the index.html i.e., for example localhost:4200 or href="/" in index.html for user module and also want to access another one is for admin module like localhost:4200/admin from the same application.. i'm not getting how to access the 2nd url.

Please help me out..

Lavanya2021 avatar Aug 02 '19 07:08 Lavanya2021

Please tell me if manually changing the URL is equivalent to clicking the refresh button. For example if a user is on a page deep inside an Angular app and wishes to reload the data there, they're likely to click the browser refresh button. Configuring the backend to redirect the browser to the app's entry page is cool but then what happens - does the router wake up in the user's browser, or does the user have to click-click-re-navigate to the old page? Thx.

chrisinmtown avatar Aug 13 '19 13:08 chrisinmtown