Rule to redirect non logged in User to Custom Registration/login Page in .htaccess file
Frage
I am trying to redirect not logged in users from the "/purchaseads/purchase.php"
to custom registration/login url "/purchaseads/registrationurl"
on wordpress website. Unfortunately when visit the url "/purchaseads/purchase.php"
even as a non logged on user nothing changes, doesn't redirect to custom register/login form.
The .httaccess snippet i am using is as follows
RewriteCond %{HTTP_COOKIE} !.*wordpress_logged_in.*$ [NC]
RewriteCond %{REQUEST_URI} ^(.*?/?)purchase.php
RewriteRule . https://%{HTTP_HOST}%1/registrationurl [L,QSA]
I am checking if this cookie is set "wordpress_logged_in"
if not redirect to custom register/login url. Not sure if this approach is secure enough. Maybe there are better ways to validate. What could be missing?
Lösung
RewriteCond %{HTTP_COOKIE} !.*wordpress_logged_in.*$ [NC] RewriteCond %{REQUEST_URI} ^(.*?/?)purchase.php RewriteRule . https://%{HTTP_HOST}%1/registrationurl [L,QSA]
This will result in a 302 (temporary) redirect to /purchaseads//registrationurl
- note the double-slash. This double-slash is passed through to the $_SERVER['REQUEST_URI']
variable that WordPress uses to route the URL. So, this may result in WP not being able to route the request.
You would need to remove the optional slash delimiter from the captured subpattern. ie. Change ^(.*?/?)purchase.php
to ^(.*?)/?purchase\.php$
(not forgetting to backslash-escape literal dots).
The second condition that checks the URL-path is not required - this check should be performed in the RewriteRule
pattern instead:
RewriteCond %{HTTP_COOKIE} !wordpress_logged_in
RewriteRule ^(.*?)/?purchase\.php$ /$1/registrationurl [R=302,L]
Your original directive would have implicitly triggered a 302 redirect (because you included an absolute URL in the substitution string), however, you should be explicit and include the R
flag. (You need to include the R
flag when the target URL is expressed as root-relative.)
The QSA
flag is not required here. Nor is the NC
flag on the preceding condition. !wordpress_logged_in
is the same as !.*wordpress_logged_in.*$
.
These directives should also go near the top of your .htaccess
file, to ensure there are no conflicts.
Not sure if this approach is secure enough.
Whether this is "secure enough" is dependent on the consequences.
What happens if this redirect does not occur? Would any information be exposed or critical action occur?
Simply checking that the string wordpress_logged_in
does not occur anywhere (not just a cookie whose name contains "wordpress_logged_in") in the Cookie
header does not reliably check that the user is not logged in. It would be relatively trivial for a malicious user to construct a request that bypassed this check.
You can't reliably determine that a user is logged in using .htaccess
.