I’m testing some stuffs on Apache server and PHP. at the root of my project, I have this
.htaccess
configuration file:
RewriteEngine On
RewriteBase /react/
# API requests
RewriteCond %{REQUEST_URI} ^/react/api/
RewriteRule ^api/(.*)$ routes/api.php?controller=$1 [QSA,L]
# Non-API requests
RewriteCond %{REQUEST_URI} !^/react/api/
RewriteRule ^(.+)$ routes/web.php?controller=$1 [QSA,L]
I want to redirect requests starting with api
to api.php
and others to web.php
. However, with the current configuration, all requests are being redirected to web.php
. I haven’t been able to identify the issue. Please help me.
(Sorry if there are any errors in my text; I’m not fluent in English.)"
I tried some much things, for example I did this:
RewriteEngine On
RewriteBase /react/
# API requests
RewriteCond %{REQUEST_URI} ^/react/api/
RewriteRule ^api/(.*)$ routes/api.php?controller=$1 [QSA,L]
# Non-API requests
RewriteCond %{REQUEST_URI} !^/react/api/
RewriteRule ^([^/]+)$ routes/web.php?controller=$1 [QSA,L]
This worked, but when I have this kind of URL localhost/react/client/something
it didn’t work.
2
Answers
I knew that I had to revise my regex expressions
I did it and it works
Because the regex
^([^/]+)$
only matches URLs with a single path segment. eg./foo
and/bar
, but not/foo/bar
or/client/something
(your example).It also doesn’t match the directory itself (an empty URL-path), so requests for
localhost/react/
would also fail.However, you do need an an additional rule (or condition) to prevent an additional pass by the rewrite engine. Or use the
END
flag (Apache 2.4) instead ofL
. Without this, an additional loop by the rewrite engine results in either:routes/web.php
a second time, at which point the rewrite engine terminates.routes/api.php
end up being rewritten toroues/web.php
instead during the 2nd pass.For example, use something like the following instead:
(Although, it would seem from your existing answer that the
controller=$1
query string is not required on the second rule. In which case, theQSA
flag is not required either, since the query string is passed through by default.)Note also that since the
.htaccess
file would seem to be in the/react
subdirectory then theRewriteBase
directive is not required.However, an additional concern with this is that all static assets (CSS, JS, images, etc.) are going to be rewritten to
web.php
as well, unless these are hosted somewhere else entirely?