Angular's RouterModule experiences persistent "404 Not Found" errors during URL navigation post-production deployment

Understanding Angular 4 Production Deployment

After successfully building my first Angular 4 app, I used angular-cli to create a production build for an Apache server on Ubuntu by executing the following command:

ng build --base-href /my-new-app/ -prod

The specific setup was necessary due to other apps hosted on the Apache server with URLs like this:

Encountering a Issue

Reviewing my app-routing-module revealed the following structure:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { MyComponent } from './my-comp/my-component.component';

const routes: Routes = [
  { path: '', redirectTo: '/my-comp', pathMatch: 'full' },
  { path: 'my-comp',  component: MyComponent },
  { path: '**', redirectTo: '/my-comp', pathMatch: 'full'}];

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

Accessing the app via redirects correctly to . However, refreshing the page or entering leads to a "404 not found" error.

During development using ng serve --host 0.0.0.0 --open, the app functions properly, but it opens on localhost:4200/my-comp, indicating there might be differences in behavior between development and production environments.

What could be causing only the initial route to work while subsequent routes result in a 404 error during production deployment?

Answer №1

To implement friendly URLs, it is recommended to create a .htaccess file in the root directory and insert the following code:

RewriteEngine On
    # Serve existing assets or directories as they are
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    # Redirect to index.html if requested resource does not exist
RewriteRule ^ /index.html

We hope this information proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Material Table with Pagination: Fetch data from server by triggering API call upon clicking on the "Next Page

When working with MatPaginator in conjunction with mat-table, what is the most effective approach for handling the next page click event? I have developed a custom DataSource with connect() and disconnect() functions. Is it necessary to explicitly manage ...

Unpredictable AWS Lambda performance when using TypeScript

After deploying my code to AWS Lambda, I noticed a strange issue. When I access the endpoint using Postman, it runs smoothly for the first time. However, upon subsequent attempts, I encounter the following error: { "error": "Validation error" } If I ...

Create a blank PDF file by converting HTML to PDF using ItextSharp

I have been using Itexsharp.dll to convert HTML to PDF in a webapi and Angular 2 project. However, I am encountering an issue where the PDF generated is blank when I try to open it in Angular 2. Here is my code: Web API code: - HttpResponseMessage respon ...

Ionic - Smooth horizontal tab scrolling for sorted categories

Currently, we are developing a web/mobile application that includes horizontal scroll tabs to represent Categories. While this feature works well on mobile devices, it requires additional functionality for web browsers. Specifically, we need to add two arr ...

What causes the website to malfunction when I refresh the page?

I utilized a Fuse template to construct my angular project. However, upon reloading the page, I encountered broken website elements. The error message displayed is as follows: Server Error 404 - File or directory not found. The resource you are looking fo ...

Display embedded ng-template in Angular 6

I've got a template set up like this <ng-template #parent> <ng-template #child1> child 1 </ng-template> <ng-template #child2> child 2 </ng-template> </ng-template> Anyone know how t ...

Guide to hosting an Angular 2 client app and Node server app simultaneously on one server

After creating an app in Angular 2 to retrieve data from a database and utilizing node/express to get data from the server and share it with the Angular client, both are currently operating on separate local hosts. How can I integrate them into one proje ...

Is it advisable to add a dataset containing arrays as attributes using a for-loop into my database?

Having just started working with MySQL, I find myself wondering about the best approach for the following problem. The object in question has the following structure: { id: number, names: [string] } When attempting to insert this object into a databa ...

Exploring CodeSandBox: Navigating the terminal within an angular project

I am trying to run some commands using ng in CodeSandBox within an Angular project. However, I am unable to locate the terminal option in my CodeSandBox environment, unlike when I work on a Node.JS project. Can someone assist me in accessing the terminal ...

The attribute 'data' is not found within the type 'Promise<void | AxiosResponse>'

I am encountering this issue: Property 'data' is missing on type 'Promise<void | AxiosResponse<{ data: { email: string; username: string; }; }, any>>'.ts(2339) when trying to make a post request like so: const sendRequest = ...

Upon closing the browser, the Angular ngx-cookie-service data disappears

Currently, I am working on setting a cookie using ngx-cookie-service so that I can retrieve it later as needed. Everything seems to be functioning properly as the code works well when refreshing the page, and the cookie is visible in Chrome developer tool ...

Setting up an angular2 web application on an Nginx server and forwarding HTTP requests to the backend API for

Seeking assistance with setting up angular2 routes and proxying http requests to a rest api on a separate server Currently, I have an angular2 web application running on an nginx server which serves the static html files. The rest api that the application ...

Learn how to connect a formArray from the parent component to the child component in Angular with reactive forms, allowing you to easily modify the values within the formArray

In my parent component, there is a reactive form with controls and a form group. When the user selects a playerType from a dropdown menu, I dynamically add a formArray to the formGroup. This form array will contain either 2 or 3 form groups based on the p ...

Retrieve the attribute of a JSON data structure

I'm encountering an issue while trying to access the property of a JSON object named date in my Angular 6 project. Even though I assigned a variable to it, it keeps showing up as undefined. This is the snippet of code causing trouble: getHistorial(d ...

[karma]: Oops! We've encountered a snag - the module [expose-loader?jQuery!jquery] couldn't be

Currently, I am working on setting up karma tests for typescript. karma.conf.js module.exports = function (config) { config.set({ frameworks: ['jasmine', 'karma-typescript'], files: [ {pattern: 'sr ...

The useEffect hook is triggering multiple unnecessary calls

Imagine a tree-like structure that needs to be expanded to display all checked children. Check out this piece of code below: const { data } = useGetData(); // a custom react-query hook fetching data from an endpoint Now, there's a function that fin ...

How to Ensure that the Hidden Value of Select Statement in Angular is Always Displayed as Text

Is there a way to customize the top part of a dropdown menu so that it always displays a specific phrase, like 'Symbols' in this case, regardless of the option selected? Currently, the top part shows the last selected symbol, but I want it to be ...

Display all values of an array in a single array using Angular

I have an array with values that are structured as shown in the image https://i.sstatic.net/SIo0N.png I am trying to consolidate them into a single array like { "1vwxnrjq", "dasdada", "adsdadsada"} console.log(items); this.ids = items.id; console.log(th ...

Setting up d3 to function properly with Angular2 and TypeScript

Attempting to integrate the d3 library into an Angular 2 TypeScript project. I installed d3 using npm install d3 and the typings using typing install d3 --save, but when trying to start the local server for the project (tsc && concurrently "npm ru ...

What is the best way to convert a recordset to an array using React?

I'm attempting to create an array by retrieving data from a SQL recordset: +------------+------------+------------+ | start_type | field_name | start_text | +------------+------------+------------+ | 0 | Field1 | some text. | +----------- ...