centos

centos laravel如何实现前后端分离

小樊
42
2025-09-26 08:30:44
栏目: 智能运维

在CentOS系统上实现Laravel前后端分离,通常涉及以下几个步骤:

  1. 安装Laravel: 首先,你需要在CentOS服务器上安装Laravel。你可以使用Composer来安装Laravel项目。

    composer create-project --prefer-dist laravel/laravel your_project_name
    
  2. 配置Nginx或Apache: 你需要配置Web服务器(如Nginx或Apache)来处理前端和后端的请求。

    • Nginx配置示例

      server {
          listen 80;
          server_name your_domain.com;
      
          root /path/to/your/laravel/public;
          index index.php index.html index.htm;
      
          location / {
              try_files $uri $uri/ /index.php?$query_string;
          }
      
          location ~ \.php$ {
              fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
              fastcgi_index index.php;
              include fastcgi_params;
              fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
              fastcgi_param PATH_INFO $fastcgi_path_info;
          }
      
          location /api/ {
              alias /path/to/your/frontend/build/;
              try_files $uri $uri/ /index.php?$query_string;
          }
      }
      
    • Apache配置示例

      <VirtualHost *:80>
          ServerName your_domain.com
      
          DocumentRoot /path/to/your/laravel/public
      
          <Directory /path/to/your/laravel/public>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
          </Directory>
      
          Alias /api /path/to/your/frontend/build
          <Directory /path/to/your/frontend/build>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
          </Directory>
      </VirtualHost>
      
  3. 配置CORS: 为了允许前端和后端之间的跨域请求,你需要在Laravel中配置CORS(跨域资源共享)。

    安装fruitcake/laravel-cors包:

    composer require fruitcake/laravel-cors
    

    config/cors.php中配置CORS:

    return [
        'paths' => ['api/*'],
        'allowed_methods' => ['*'],
        'allowed_origins' => ['*'],
        'allowed_origins_patterns' => [],
        'allowed_headers' => ['*'],
        'exposed_headers' => [],
        'max_age' => 0,
        'supports_credentials' => false,
    ];
    
  4. 前端构建: 在前端项目中运行构建命令,生成静态文件。

    cd /path/to/your/frontend
    npm install
    npm run build
    
  5. 运行Laravel后端: 启动Laravel后端服务。

    cd /path/to/your/laravel
    php artisan serve --host 0.0.0.0 --port 8000
    

    或者使用Gulp、Supervisor等工具来管理Laravel后端服务。

  6. 测试: 确保前端和后端都能正常访问,并且跨域请求能够成功。

通过以上步骤,你可以在CentOS系统上实现Laravel前后端分离。前后端分别部署在不同的目录或服务器上,通过API进行通信。

0
看了该问题的人还看了