WordPress .htaccess rule only for frontend (logged out)

So I added some apache .htaccess rows to the .htaccess in my WordPress setup and found the /wp-admin/ was not working anymore. It redirected me to the frontend and I was stuck… The rules worked as wanted frontend, but broke the backend. I needed one extra row to say: ‘only do it frontend’.

This is what I started with:

# Force trailing slash
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_METHOD} GET
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{REQUEST_FILENAME} !\.(gif|jpg|png|jpeg|css|xml|txt|js|php|scss|webp|mp3|avi|wav|mp4|mov)$ [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1/ [L,R=301]

The first row activates the rewrite possibility. Then there are some conditions (RewriteCond): if it is not a file, not a GET request, does not end with a slash and is not a file with one of the specified extensions. If all are true, add a slash to the request url. I needed one more line with something like ‘not logged in’

There are WordPress functions that check for the loggedin state, but PHP does not work in .htaccess. The solution was to check the cookies:

RewriteCond %{HTTP:Cookie} !(wordpress_logged_in_|wp-postpass_|wptouch_switch_toggle|comment_author_|comment_author_email_) [NC]

If I add that line before the RewriteRule, the slash is only added if the user is not logged in, hence the RewriteRule will never affect the admin area as you need to be logged in to access the admin area.

The complete set:

# Force trailing slash
RewriteEngine On
RewriteCond %{HTTP:Cookie} !(wordpress_logged_in_|wp-postpass_|wptouch_switch_toggle|comment_author_|comment_author_email_) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_METHOD} GET
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{REQUEST_FILENAME} !\.(gif|jpg|png|jpeg|css|xml|txt|js|php|scss|webp|mp3|avi|wav|mp4|mov)$ [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1/ [L,R=301]