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

部署于Amazon Linux 2 AMI的Laravel API路由问题:访问API出现403 Not Found错误求助

Troubleshooting Laravel API 403 Error on Amazon Linux 2 EC2

Alright, let's tackle this 403 issue with your Laravel API on Amazon Linux 2 EC2. Since the welcome page loads fine, we know the core Laravel setup is working—so the problem is almost certainly tied to routing, server config, permissions, or CSRF protection. Here's how to debug step by step:

1. Verify API Routing & HTTP Method

  • First, double-check that your API routes are defined in routes/api.php (not web.php). Laravel automatically prefixes these routes with /api, so if your endpoint is supposed to be /api/user, make sure you're hitting that exact path in Postman.
  • Confirm the HTTP method matches what's defined in your route. For example, if you have Route::post('/submit', [FormController::class, 'submit']), sending a GET request to that endpoint will throw an error.
  • Run php artisan route:list in your project root to see all registered routes. This will show you the full path, HTTP method, and controller action for each route—verify your target API endpoint is listed correctly.

2. Fix Server URL Rewrite Configuration

Laravel relies on URL rewriting to route requests to index.php (the front controller). If this isn't set up right, only the root path (welcome page) will work, and all other routes will return 403/404.

For Apache:

  • Enable the mod_rewrite module if it's not already on:
    sudo a2enmod rewrite
    
  • Ensure your project's public/.htaccess file has the default Laravel rewrite rules (if it's missing, copy it from the Laravel template):
    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
            Options -MultiViews -Indexes
        </IfModule>
    
        RewriteEngine On
    
        # Handle Authorization Header
        RewriteCond %{HTTP:Authorization} .
        RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    
        # Redirect Trailing Slashes If Not A Folder...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_URI} (.+)/$
        RewriteRule ^ %1 [L,R=301]
    
        # Send Requests To Front Controller...
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [L]
    </IfModule>
    
  • Update your Apache virtual host config (usually in /etc/httpd/conf.d/ or /etc/httpd/sites-available/) to allow .htaccess overrides:
    <Directory /var/www/html/your-project/public>
        AllowOverride All
        Require all granted
    </Directory>
    
  • Restart Apache to apply changes:
    sudo systemctl restart httpd
    

For Nginx:

  • Open your Nginx site config (typically in /etc/nginx/conf.d/ or /etc/nginx/sites-available/) and make sure it includes the correct try_files rule to route all requests to index.php:
    server {
        listen 80;
        server_name your-domain-or-ec2-ip;
        root /var/www/html/your-project/public;
    
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-Content-Type-Options "nosniff";
    
        index index.php;
    
        charset utf-8;
    
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
    
        location = /favicon.ico { access_log off; log_not_found off; }
        location = /robots.txt  { access_log off; log_not_found off; }
    
        error_page 404 /index.php;
    
        location ~ \.php$ {
            fastcgi_pass unix:/var/run/php-fpm/www.sock;
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            include fastcgi_params;
        }
    
        location ~ /\.(?!well-known).* {
            deny all;
        }
    }
    
  • Test the Nginx config for syntax errors:
    sudo nginx -t
    
  • If no errors, restart Nginx:
    sudo systemctl restart nginx
    

3. Correct File & Directory Permissions

Laravel needs write access to the storage and bootstrap/cache directories to function properly. Incorrect permissions can cause 403 errors or internal server errors.

  • Set the correct ownership (use apache for Apache, nginx for Nginx):
    sudo chown -R apache:apache /var/www/html/your-project
    
  • Grant write permissions to the required directories:
    sudo chmod -R 755 /var/www/html/your-project/storage
    sudo chmod -R 755 /var/www/html/your-project/bootstrap/cache
    

4. Check CSRF Protection

Laravel's web middleware group enforces CSRF protection, but the api group does not by default. If your API routes are accidentally in routes/web.php, POST/PUT/DELETE requests will fail with a 403 because they lack a CSRF token.

  • Move your API routes to routes/api.php (preferred), or add your API paths to the CSRF exception list in app/Http/Middleware/VerifyCsrfToken.php:
    protected $except = [
        '/api/*',
    ];
    

5. Verify EC2 Security Group & Firewall Settings

  • Ensure your EC2 security group allows inbound traffic on port 80 (HTTP) or 443 (HTTPS). You can check this in the AWS Console under EC2 > Security Groups.
  • Check Amazon Linux 2's built-in firewalld to make sure it allows HTTP/HTTPS traffic:
    sudo firewall-cmd --add-service=http --permanent
    sudo firewall-cmd --add-service=https --permanent
    sudo firewall-cmd --reload
    

6. Check Laravel Logs for Detailed Errors

If none of the above fixes work, check Laravel's log file for specific error details. This will often point you directly to the issue:

cat /var/www/html/your-project/storage/logs/laravel.log

内容的提问来源于stack exchange,提问作者Shameer Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 13:42:51