Reputation: 3580
I'm stuck on a problem with correct .htaccess in my restful webapp. My REST api code shall be accessible via the URL-pattern */api/** which should be redirected to index.php in the api folder.
All other URLs (except static files) shall be redirect to index.html in the root folder.
I have following folder structure:
- api -- application/... -- vendor/... -- index.php - public -- css/... -- js/... - index.html - .htaccess
And this is my .htaccess content:
Options +FollowSymLinks
RewriteEngine on
# redirect all api calls to /api/index.php
RewriteCond "%{REQUEST_URI}" "^/api"
RewriteRule "^/api/(.+)$" "/api/index.php$" [QSA,L]
# If the request is a file, folder or symlink that exists, serve it up
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+)$ - [S=1]
# otherwise, serve your index.html app
RewriteRule ^(.+)$ /index.html [L]
I have tried to add another .htaccess to the api folder, to redirect the URLs with /api/* but without any success. So I tried to redirect it with a rule in the .htaccess above.
I think the lower to rules might be correct. Because the redirecting is working as expected. But the /api/ rule does not work. It seems that the requests also redirected to the index.html
What am I missing?
Upvotes: 2
Views: 9448
Reputation: 785196
Minor tweaks of your regex pattern is what you need:
DirectoryIndex index.php index.html
Options +FollowSymLinks
RewriteEngine on
# redirect all api calls to /api/index.php
RewriteRule ^api/((?!index\.php$).+)$ api/index.php [L,NC]
# If the request is a file, folder or symlink that exists, serve it up
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# otherwise, serve your index.html app
RewriteRule ^(.+)$ index.html [L]
Upvotes: 6
Reputation: 80639
Try the following set of rules:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/api/index\.php$ [NC]
RewriteCond %{REQUEST_URI} ^/api [NC]
RewriteRule ^api/.* /api/index.php$ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l # to check for symbolic links
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /index.html [L]
RewriteRule . - [L]
Upvotes: 1