1
votes

I have a bit of an odd problem. My rewrite rules appear to work just as I would expect, but not for sub-pages.

www to none www always works, but forcing https does not work on some pages.

All rules do work however on the home page, so that's all good.

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

# www and https rules.
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</IfModule>

Results:

  1. http://example.com -> https://example.com (good)
  2. http://www.example.com -> https://example.com (good)
  3. https://example.com -> https://example.com (good)
  4. https://www.example.com -> https://example.com (good)

However, sub-pages do not appear to be working correctly:

  1. https://example.com/page -> https://example.com/page (good)
  2. https://www.example.com/page -> https://example.com/page (good)
  3. http://example.com/page -> http://example.com/page (bad)
  4. http://www.example.com/page -> http://example.com/page (bad)

Any idea how I can improve this rewrite to work with no www and https regardless of my location?

Thanks

2

2 Answers

2
votes

Replace your rules with this:

RewriteEngine On
RewriteBase /

# remove www and turn on https in single rule
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

Ordering is important so you must keep redirect rule before WP default rules. Also make sure to clear browser cache when testing this change.

1
votes

In your www and https rules. block you redirect to HTTP:

RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

As you want to always redirect to HTTPS, make it redirect to HTTPS as well:

RewriteRule ^(.*)$ https://%1/$1 [R=301,L]