Search code examples
apache.htaccessmod-rewriteurl-rewritingforwarding

htaccess rewrite to require www, https, and ip


I am trying to figure out how to write the .htaccess so that all URLs: 1) Use https 2) Forward from http://example.com to https://www.example.com 3) Forward from the server IP to the domain

I tried:

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} ^111\.11\.111\.111
RewriteRule ^ https://www.{HTTP_HOST}/%{REQUEST_URI} [L,R=301]

But this doesn't work. The IP is the actual server IP.

What am I doing wrong?


Solution

  • You can do all this in a single rule:

    RewriteEngine On
    
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301,NE]