You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 6与Angular部署后刷新页面出现404错误的求助

问题原因

Angular是单页应用(SPA),所有前端路由都是通过routerLink在浏览器端处理的。当你刷新页面时,浏览器会直接向服务器请求当前URL对应的资源,但服务器上并没有/tinghirs这类路径的物理文件,因此返回404错误。需要配置服务器,让所有前端路由请求都转发到Angular的入口文件index.html,同时保证Laravel的API路由能正常处理。

解决方案

1. Apache服务器配置

如果你的服务器使用Apache,在Laravel的public目录下修改或创建.htaccess文件,添加以下重写规则:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # 优先处理Laravel API路由
    RewriteCond %{REQUEST_URI} ^/api/
    RewriteRule ^ index.php [L]

    # 所有非文件、非目录的请求转发到Angular的index.html
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.html [L]
</IfModule>

注意:确保Angular构建后的所有文件都放在Laravel的public目录下,服务器才能正确找到index.html。

2. Nginx服务器配置

若使用Nginx,修改站点配置文件,添加如下规则:

server {
    listen 80;
    server_name www.aswaktinghir.com;
    root /path/to/laravel/public; # 替换为你的Laravel public目录路径
    index index.html index.php;

    # 处理API请求,转发到Laravel的index.php
    location /api {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # 处理Angular前端路由,非文件请求直接指向index.html
    location / {
        try_files $uri $uri/ /index.html;
    }

    # PHP文件处理规则
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整路径
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

配置完成后重启Nginx:sudo systemctl restart nginx

3. 切换Angular路由为哈希模式(可选)

如果不想修改服务器配置,可以让Angular使用哈希模式路由,URL会带上#(如https://www.aswaktinghir.com/#/tinghirs),这种模式下刷新页面不会触发服务器请求,由前端直接处理路由。

修改Angular的app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes, HashLocationStrategy, LocationStrategy } from '@angular/router';
// 导入你的组件

const routes: Routes = [
  // 你的路由配置
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
export class AppRoutingModule { }

此方案无需服务器配置,但URL会带有#,若追求干净URL建议优先使用服务器配置方案。

4. 确保Laravel API路由前缀统一

将Laravel的所有API路由放在routes/api.php中,这类路由默认会自动带上/api前缀,这样服务器配置中的规则会将/api开头的请求转发到Laravel处理,避免与前端路由冲突。

示例Laravel API路由:

// routes/api.php
Route::get('/tinghirs', 'TinghirController@index');

内容的提问来源于stack exchange,提问作者marzouk najib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 22:53:10