Customizing WordPress .htaccess file redirects and make them stick.
August 11th 2015
Problem – Stop WordPress from rewriting our https redirects.
As part of redirecting our clients http site to https we needed to tell WordPress and well really browsers in general that when they come to an http page to instead go to the https version.
We did this and all was well until about 5 days later we notice the redirects were gone and it was back to http. So we fixed it again then randomly some days later back to http.
Well it turns out that if you change a permalink structure WordPress will rewrite the .htaccess file to reflect this (no surprise). It also turns out that WordPress will sometimes just randomly rewrite the .htaccess (surprise) for a reason that well we don’t have the answer too.
So we were getting our .htaccess file rewritten randomly and causing our https redirects to fail.
Solution – How do you prevent WordPress from rewriting .htaccess file redirects?
By default WordPress is going to have something similar to this that it will want to return to:
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
While we wanted to have something like this to do our https redirects:
# BEGIN WordPress
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
The solution then is that WP will rewrite anything in between # BEGIN WordPress and # END WordPress
So we had to take out the offending code and put it into it’s on block like so:
# BEGIN WordPress —- We are maintaining the default WP write based on our permalinks sturcture
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress —- We close it here knowing now that WP will only rewrite to default what is between the BEGIN and END – since this is default we are safe.
# Our code taking out of the WordPress .htaccess rewrite danger area – containing the correct https redirect code.
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
And Viola! everything works and we have not been re-written or broken in a while. Feel free to copy and paste that code and try it out – maybe take out our comments.
Thanks for reading and let us know if you have any questions or comments.