Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite rules not working for Drupal 7 in subfolder

So I have a site that is run at example.com and serves as a gateway for the Drupal site that runs in folder /drupal. What I want to do, I want to set a cookie on that gateway page on login and then allow access to example.com/drupal and if the cookie is not set, redirect back to example.com.

But my problem is, the rule does not work in the /drupal folder in drupal .htaccess, but I tested it and it works fine in the root directory.

The rule is as follows

   RewriteCond %{HTTP_COOKIE} !CookieName=test [NC]
   RewriteRule .* http://example.com [L]

But for some reason, the rule does not work here and the user can access the /drupal folder without the cookie, but if I place the same rule in / root, then the redirect happens since no cookie with that name is set.

like image 985
The Law Avatar asked Jul 28 '18 08:07

The Law


1 Answers

Quick test on my side to make sure it works, here is an example

/.htaccess

RewriteEngine On

# if no "logged_in" cookie set to "yes", then create it
# cookie is valid for any hosts of .example.com, during 1 minute, for the entire website, not necessarily ssl only, not accessible from javascript
RewriteCond %{HTTP_COOKIE} !logged_in=yes [NC]
RewriteRule ^ - [CO=logged_in:yes:.example.com:1:/:false:true]

See this link for the CO flag documentation (how to create a cookie through mod_rewrite)

/drupal/.htaccess

RewriteEngine On

RewriteCond %{HTTP_COOKIE} !logged_in=yes [NC]
RewriteRule ^ /index.php [R,L]

Scenario

  1. Go to /drupal/ and you should get a redirect to root index
  2. Go back to /drupal/ and it should be OK (since root index has created the cookie)
  3. Refresh the current page (/drupal/) as many as you want during 1 minute, then you'll get a redirect to root index again (cookie has expired)

Two reasons come to my mind on why you can't make it work

  1. You didn't set your cookie properly
  2. Your /drupal/.htaccess rule is not executed because placed after main-default rule (put it in the top to make sure)
like image 75
Justin Iurman Avatar answered Oct 21 '22 08:10

Justin Iurman