Question

I have the following setup in my .htaccess file, but I am still able to go to my site via http:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# Rewrite HTTP to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]
</IfModule>

# END WordPress

Any idea what I could be doing wrong?

Was it helpful?

Solution

You've put the code in the wrong place. The HTTP to HTTPS directives must go before the WordPress front-controller, otherwise it's simply never going to get processed for anything other than direct file requests.

Your custom directives should also be outside the # BEGIN WordPress block, otherwise WordPress itself is likely to override your directives in a future update.

For example:

# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} !=on
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]    
</IfModule>
# END WordPress

It is a "redirect", not a "rewrite". Change the R to R=301 when you are sure it's working OK (as this should ultimately be a permanent redirect).

OTHER TIPS

Are you familiar with the [L] flag for mod_rewrite? It "causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed".

See: https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_l

Note that that your rewrite rules above the http->https rule employ this flag. These rules look like WordPress' rules that redirect requests that aren't for a specific file or directory to index.php for handling.

One idea is changing the order so your rules appear after Rewrite Engine On so the http-vs-https check is performed first, the redirect can take place, and then on the following redirected request (which will now be https) the following set of rules related to WordPress functionality can apply.

You could also try writing RewriteCond {HTTPS} != on as RewriteCond %{HTTPS} off and your RewriteRule line as RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] to be more explicit and send an http 301 (permanent) redirect status code back.

EDIT: I just saw MrWhite's comment, we were writing at the same time. He also has good advice: put your revised rules outside of the #WORDPRESS comment block so future WordPress updates will not clobber them!

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top