sidyll
sidyll

Reputation: 59297

Stop Rewrite If Redirected Internally

My current project uses a file structure with a public folder and main entry point (index.php) in the project root:

root/
  .htaccess
  index.php
  public/
    style.css

In order to make it work, I'm using this .htaccess:

RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -f
RewriteRule .* /public/$0 [END]

RewriteRule . index.php

This works fine and if I access [site]/style.css it gets loaded properly. Anything else goes to index.php.

However I need to use this under Apache 2.2 where the END flag is not available. If I use L:

RewriteRule .* /public/$0 [L]

It stops working because on the next iteration the condition doesn't match anymore and I end up with index.php handling it again.

How can I simulate the effect of END? I tried adding a guard before final redirect:

RewriteCond %{REQUEST_URI} !^/public/.+
RewriteRule . index.php

But this allows [site]/public/style.css to be accessed. I'd like this to be redirected by index.php to return a 404. So, in other words, how can I prevent a rewrite if the URL has already been rewritten by the former rule?

Upvotes: 1

Views: 32

Answers (1)

anubhava
anubhava

Reputation: 785276

You can use these rules on Apache 2.2:

DirectoryIndex index.php
RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -f
RewriteRule .* public/$0 [L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule . index.php [L]

Due to RewriteCond last rule will be executed only when first rule hasn't executed at all because Apache sets %{ENV:REDIRECT_STATUS} to 200 after successful execution of an internal rewrite rule.

Upvotes: 1

Related Questions