Radley Sustaire
Radley Sustaire

Reputation: 3399

Simple rewritecond in htaccess doesn't work as expected

This is super simple but it's driving me crazy! I have a website at http://example.org/ and a subdirectory at http://example.org/ccc/

I want to redirect anything outside of the /ccc/ directory to a different website.

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/ccc/?.*
RewriteRule ^(.*)$ https://new-website.com/$1 [L]

But this code doesn't work, it redirects the /ccc/ directory. According to my research and testing with this htaccess tester, it should not redirect because the RewriteCond is checking against /ccc with optional slash and other characters after it.

What is happening? Does this look correct?

Edit: This method from this answer is also not working, the CCC domain is being redirected:

RewriteEngine on
RewriteRule ^ccc index.php [L]
RewriteRule (.*) https://new-website.com/$1 [R=301,L]

PHP 5.4.45, Apache/2.2.31

Upvotes: 1

Views: 28

Answers (2)

Radley Sustaire
Radley Sustaire

Reputation: 3399

It looks like [L] isn't behaving normally and I'm guessing it's the old version of Apache (2.2.31) because these rules worked on a separate website. I found this solution which seemed to work for this case, the third line below:

RewriteEngine on
RewriteRule ^ccc/? index.php [L]
RewriteCond %{ENV:REDIRECT_STATUS} != 200
RewriteRule ^(.*)$ https://new-website.com/$1 [L]

Explanation from that question:

The problem is that once the [L] flag is processed, all the next RewriteRules are indeed ignored, however, the file gets processed AGAIN from the begin, now with the new url.

This magic Condition will not process the catch all if the file was already redirected.

Upvotes: 0

anubhava
anubhava

Reputation: 784868

Assuming ccc/ directory doesn't have a separate .htaccess, you may use this rule:

RewriteEngine on

RewriteCond %{THE_REQUEST} !\s/ccc[/?\s] [NC]
RewriteRule ^ https://new-website.com%{REQUEST_URI} [L,R=301,NE]

THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of other rewrite directives. An example value of this variable is GET /index.php?id=123 HTTP/1.1

Upvotes: 1

Related Questions