Search code examples
laravelapache.htaccessmod-rewrite

.htaccess rewrite to index.php or index.html based on condition


I'm not so good with htaccess and tried to find an answer to my question but no luck so far.

So I have this .htaccess rewrite:

RewriteCond %{REQUEST_URI} /(api|nova|nova-api)
RewriteRule .* /index.php

Which works well.

The website is an Angular site where I have dynamic URLs which are routed by JS.

So if I open base domain: example.com works well because index.html is served.

But if I open a route like: example.com/example-route. It says 404.

Could you please help me how should I modify the .htaccess file?


Solution

  • RewriteCond %{REQUEST_URI} /(api|nova|nova-api)
    RewriteRule .* /index.php
    

    You would seem to just need to rewrite the request to index.html after your API rewrite to index.php. However, you should modify your existing rule to add the L flag and the regex that matches the request should be anchored (although the condition is not required at all since the URL check should be performed in the RewriteRule directive itself).

    For example, try the following instead:

    # "index.html" needs to take priority when requesting the root directory
    DirectoryIndex index.html
    
    # Abort early if request is already "index.html" or "index.php"
    RewriteRule ^index\.(html|php)$ - [L]
    
    # Rewrite certain requests to Laravel API
    RewriteRule ^(api|nova|nova-api)($|/) index.php [L]
    
    # Rewrite everything else to Angular
    # (unless it already maps to a file or directory)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.html [L]
    

    Since the "homepage" is already working OK, it would suggest DirectoryIndex is already set OK in the server config (and prioritising index.html), although explicitly setting this to just index.html (as above) is more optimal, if this is all that's required.