Jelly
Jelly

Reputation: 37

Rewrite rule only if other rules do not apply

I have the following rules:

RewriteRule ^error$ 404.php
RewriteRule ^home$ index.php

Now I want, that everything behind domain.com<> (in the <>) redirects to test.php.

I did RewriteRule ^([^/]+)$ test.php

and that works but when I enter "error" or "home" it also redirects to test.php instead of to 404.php and index.php

Upvotes: 0

Views: 1561

Answers (3)

Clinton
Clinton

Reputation: 1196

You can tell the rewrite that it has completed when a matching condition is found and therefore not to continue when the condition is met so your rewrites could be something like this:

RewriteEngine On
RewriteBase /
RewriteRule ^error$ 404.php [L,NC]
RewriteRule ^home$ index.php [L,NC]
RewriteRule ^(.*)$ test.php

The 'L' rewrite flag tells the redirect that this is the last condition (i.e. look no further). The 'NC' flag make the rule case insensitive. You can decide if this you also want to include need a R=301 flag or not.

However, I can see a potential issue in the above because once the rules have been processed, the rewritten request is handed back to the URL parsing engine and the rewritten request is handled again by the .htaccess file. This will cause the second last rule to be accepted on the second pass.

The alternative [END] flag, can be used to terminate not only the current round of rewrite processing but prevent any subsequent rewrite processing from occurring in the htaccess context. I will be interested if this works.

Hope this helps.

Upvotes: 0

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

Try this :

RewriteEngine On
RewriteRule ^error$ 404.php 
RewriteRule ^home$ index.php
RewriteCond %{REQUEST_URI} !/(error|home|index|404)
RewriteRule ^([^/]+)$ test.php

The problem is that , you have already captured error and home but when they redirected to 404 or index they being captured again by the last rule so you should exclude them from last rule.

Upvotes: 0

anubhava
anubhava

Reputation: 785256

You can REDIRECT_STATUS like this:

RewriteEngine On
RewriteBase /

RewriteRule ^error/?$ 404.php [L,NC]
RewriteRule ^home/?$ index.php [L,NC]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^ test.php

REDIRECT_STATUS gets set to non-zero value (200) after execution of some rewrite rules.

Upvotes: 1

Related Questions