php – 404 not found on Laravel API routes using nginx-ThrowExceptions

Exception or error:

I am trying to set up a server with PHP 7.2 and nginx. I can get the laravel homepage to load when I navigate to my-site.com/snow however I can’t get any of the API routes defined in API.php to load. All of my API routes are prefixed with /api/ like /api/login. I get a 404 error on all my API routes. What am I doing wrong?

location ~ \.php$ {
  include snippets/fastcgi-php.conf;
  # With php-fpm (or other unix sockets):
  fastcgi_pass unix:/run/php/php7.2-fpm.sock;
  # With php-cgi (or other tcp sockets):
  # fastcgi_pass 127.0.0.1:9000;
}

location /snow {
  index index.php;
}

location /snow/api {
  root /var/www/html/snow;
  rewrite ^/api/(.*)$ /$1 break;
  try_files $uri $uri/ /api/index.php$is_args$args;
}

location ~ snow/api/.+\.php$ {
  root /var/www/html/snow;
  rewrite ^/api/(.*)$ /$1 break;
  #include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/run/php/php7.2-fpm.sock;
}

.htaccess

Options -Indexes
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

<Files .env>
    Order allow,deny
    Deny from all
</Files>

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
How to solve:

If you’re using the api.php routes file, Laravel already prefixes those routes with /api, so you may be duplicating that in your config. Check if /api/api/login works.

If the above works, you don’t need the two /api rules in your nginx config. Once you remove those rules, you should be able to access the APIs using /api/login.

You can also try updating your nginx config to the following, as your current config doesn’t appear to be pointing to the public directory of Laravel:

location /snow/api {
  root /var/www/html/snow/pubic;
  try_files $uri $uri/ /index.php?$query_string;
}

Answer´╝Ü

i had the same issue

i replaced

try_files $uri $uri/ =404;

with

try_files $uri $uri/ /index.php$is_args$args;

and it worked.

Leave a Reply

Your email address will not be published. Required fields are marked *