How to redirect non-logged in users using RewriteRule in htaccess

Redirect non-logged in users using htaccess

With apache mod-rewrite it is quite possible to manipulate http cookies. The cookie you set using php or RewriteRule can easily be accessed using RewriteCond directive.
If you need to redirect your non-logged in users of your website to a diffrent page using RewriteRule you need to check the COOKIES in RewriteCond directive .
You can use %{HTTP_COOKIE} variable which is a pre defined mod-rewrite variable to check if the user visiting your site has cookies set.
Assuming the following user cookie is set user=loggedin
You can simply use a RewriteRule to redirect your non-logged in users to a diffrent page based on if the cookie exists.

RewriteEngine on
RewriteCond %{HTTP_COOKIE} !^user=loggedin$ [NC]
RewriteRule ^ /page2.php [L,R]

The rewrite rule above will redirect user to /page2.php if the cookie user=loggedin doesnt exist or isnt set. The rule also redirects files like css , js and other website resources. You can simply add other conditions to exclude your existent files so that it can only redirect the user request. The following rule should work in that case :

RewriteEngine on
#exclude files
RewriteCond %{REQUEST_FILENAME} !-f
#exclude dirs
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{HTTP_COOKIE} !^user=loggedin$ [NC]
RewriteRule ^ /page2.php [L,R]

Leave a Reply

Your email address will not be published. Required fields are marked *