Search code examples
.htaccesssslno-www

.htaccess non www to no www SSL and www to www SSL


I have searched every where and tried various .htaccess configurations, but haven't found an answer.

With access to only the .htaccess file I want to:

Direct NON www to NON www SSL Example: http://example.com -> https://example.com

AND

Direct www to www SSL Example: http://www.example.com -> https://www.example.com

Most examples show forcing all requests to SSL as only NON www or www. I want both.

htaccess

<IfModule mod_headers.c>
  Header append Vary: User-Agent
  Header append Vary: Accept-Encoding
</IfModule>

AddDefaultCharset utf-8
AddType image/svg+xml svg

RewriteEngine On

RewriteRule ^sitemap\.xml$ /sitemap.php [L]

# Exception - Reached the document root then stop
# (Prevents rewrite loop if index.php is missing - 404 instead)
RewriteRule ^index\.php$ - [L]

# Exception - Any request for a valid file stop here
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# If already requesting "index.php" then step up a directory
RewriteRule ^(.*/)?[^/]+/index\.php$ /$1index.php [L]

# Otherwise try "index.php" in the current path segment
RewriteRule ^(.*/)?[^/]*$ /$1index.php [L]

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilter DEFLATE .shtml
</IfModule>

<IfModule mod_expires.c>
ExpiresActive On
AddType image/x-icon .ico
ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType image/ico "access plus 1 year"
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/svg "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>

Solution

  • You can use:

    RewriteEngine on 
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]