I have a directory structure as follows:
.htaccess
api.php
template/index.html
When calling domain.com/api/someendpoint
, the request is forwarded to api.php
.
# enable apache rewrite engine
RewriteEngine on
# Deliver the folder or file directly if it exists on the server
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{REQUEST_FILENAME} !-d
# Push every request to api.php
RewriteRule ^(.*)$ api.php [QSA]
now, when calling domain.com
, the request should be called to the index.html
in the template directory:
RewriteCond %{REQUEST_URI} ^$
RewriteRule . template/index.html [QSA]
this does not work, the directoryListening is always displayed.
What is the correct way to get the index.html
?
CodePudding user response:
RewriteCond %{REQUEST_URI} ^$ RewriteRule . template/index.html [QSA]
The RewriteRule
pattern (ie. .
) unnecessarily matches everything except the document root. And the REQUEST_URI
server variable always starts with a slash, so the condition will never match anyway. So, basically, the rule is doing nothing
To rewrite just the root then you just need a single rule in .htaccess
:
RewriteRule ^$ template/index.html [L]
Ideally, this would go before your existing rewrites for your API, although it doesn't strictly matter since the other rewrites do not rewrite the root directory (because of the restrictive conditions).
# Push every request to api.php RewriteRule ^(.*)$ api.php [QSA]
Should everything really be sent to api.php
, or perhaps just URLs that start /api/
, as in your example? At the very least, you should be using the
quantifier, not *
, since you want to exclude requests for the document root (currently, the 3rd condition is blocking requests to the document root from being rewritten).
Note that if your URLs are of the form /api/someendpoint
and you are rewriting to /api.php
then you need to ensure that MultiViews is disabled at the top of the .htaccess
file:
Options -MultiViews