htaccess - Remove www and selectively force https - apache

Having a difficult time finding the combination to satisfy the following 3 conditions. What Rewrite rules and conditions will accomplish the conditions? (I've already been surprised by the rules not working.)
www stripped from all requests
https for all requests to primary
http for all requests to subdomain (in subfolder of main site) subdomain.com
htaccess:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.primary\.mobi [NC,OR]
RewriteCond %{HTTP_HOST} ^primary\.mobi [NC,OR]
RewriteCond %{HTTP_HOST} !^(www\.)?subdomain\.com [NC]
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
The above do not strip www and send www.subdomain to https.
Explanations welcomed. Trying to understand the apache mod_rewrite manual page and have tried several methods without success.

You can capture the domain and use it in your RewriteRule. HTTP_REQUEST is not available in the substitution part, but only in RewriteCond directives.
I'm not sure, but you can try to split this into two .htaccess files. This one goes into the main directory
RewriteEngine On
# remove www. from HTTPS requests
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(primary\.mobi)$ [NC]
RewriteRule .* https://%1/$0 [R,L]
# redirect HTTP requests to HTTPS
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(primary\.mobi)$ [NC]
RewriteRule .* https://%1/$0 [R,L]
and this is for the .htaccess in the subdomain folder
RewriteEngine On
# remove www. from HTTP requests
RewriteCond %{HTTP_HOST} ^www\.(subdomain\.com)$ [NC]
RewriteRule .* http://%1/$0 [R,L]
# redirect HTTPS requests to HTTP
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(subdomain\.com)$ [NC]
RewriteRule .* http://%1/$0 [R,L]
Test your rules without 301, because the browser caches 301 results and makes testing much harder. Add R=301 not until you're satisfied with the rules.
In Canonical Hostnames are some alternatives described, especially the first one, using virtual hosts, looks promising
<VirtualHost *:80>
ServerName www.primary.mobi
Redirect / https://primary.mobi/
</VirtualHost>
<VirtualHost *:80>
ServerName primary.mobi
</VirtualHost>
<VirtualHost *:80>
ServerName www.subdomain.com
Redirect / http://subdomain.com/
</VirtualHost>
<VirtualHost *:80>
ServerName subdomain.com
</VirtualHost>
I don't know, if this is feasible for you, but you might try.

Related

Https redirection not working on Apache 2.4

I had some issues with my apache configuration and I'm trying to isolate the problem.
I came up with the following lines which are not working :
For testing purposes, I'm trying to redirect all https traffic to Yahoo
The redirection is not working and my web site is showing the index.html file stored in public_html
Listen 443
NameVirtualHost *:443
<VirtualHost *:443>
DocumentRoot "${SRVROOT}/htdocs/example.com/public_html"
ServerName example.com
ServerAlias example
Redirect permanent / https://www.yahoo.com/
</VirtualHost>
Can anyone help please ?
Thanks
Use this for the redirect, also enable mod_rewrite for this to work:
Add this to the top of your .htaccess file:
RewriteEngine On #Don't use RewriteEngine On twice in one .htaccess file
RewriteBase /
RewriteRule ^(.*)$ https://www.yahoo.com [R=301,L]
Clear your browser's cache to have a different redirect than yahoo.com, once it works.
Just in case
If you want all traffic of your website to redirect to https:// on the same domain, do the following, don't remove RewriteEngine On and RewriteBase /:
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
If you want to redirect all traffic to one domain with https:
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST] !^example.com
RewriteRule ^(.*)$ https://example.com [R=301,L]
If you want to redirect all traffic to one domain with https and www:
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST] !^www.example.com
RewriteRule ^(.*)$ https://www.example.com [R=301,L]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}

URL Rewriting http > https AND domain.tld > www.domain.tld

I want to rewrite and redirect my http:\\www.domain.tld to https:\\www.domain.tld
And I want to rewrite and redirect my domain.tld to www.domain.tld
I want to have something that redirect and, with seo concern, shows that's a redirection.
For now I have something like this:
1)
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE,QSA]
or
2)
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE,QSA]
What's the best? Is there something wrong?
Thank you
The Apache docs recommend against using a rewrite: redirect to https
To redirect http URLs to https, you should do the following:
<VirtualHost *:80>
ServerName www.example.com
Redirect / https://www.example.com/
</VirtualHost>
<VirtualHost *:443>
ServerName www.example.com
# ... SSL configuration goes here
This snippet should go into main server configuration file, not into .htaccess as asked in the question.
But if you don't have access to the main server configuration file you could use this:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
Line 1: if the url starts without www
line 2: if there is no https
line 3: rewrite all urls from this domain to one that starts with https and have www

.htaccess redirect olddomain/folder to newdomain/otherfolder

I use this in my httpd.config and it works:
<VirtualHost *:80>
ServerName olddomain.com
ServerAlias www.olddomain.com
Redirect permanent /FolderName/Filename_with_underscores.html http://newdomain.com/some-folder-with-dashes/?lang=fr
Redirect permanent /FolderName/Other_filename.html http://newdomain.com/some-other-folder/?lang=fr
Redirect permanent / http://newdomain.com/
</Virtualhost>
Now I'd like to put this in the .htaccess file in the root of the website.
I have tried several things but it keeps failing.
Does anyone know how to translate this httpd redirect to .htaccess?
There are capitals, dashes and underscores in the url's...
The code below works (but it's only half the story: it redirects all (www.)olddomain.com to the desired folder at newdomain.com):
RewriteCond %{HTTP_HOST} ^olddomain\.com\$ [OR]
RewriteCond %{HTTP_HOST} ^www\.olddomain\.com$
RewriteRule ^/?$ "http://newdomain.com/some-folder-with-dashes/?lang=fr" [R=301,L]
Thnx
You can use in your root .htaccess:
RewriteEngine on
# All rules only for olddomain.com
RewriteCond %{HTTP_HOST} !^(www\.)?olddomain\.com$ [NC]
RewriteRule ^ - [L]
RewriteRule ^FolderName/Filename_with_underscores\.html$ http://newdomain.com/some-folder-with-dashes/?lang=fr [NC,R=301,L]
RewriteRule ^FolderName/Other_filename\.html$ http://newdomain.com/some-other-folder/?lang=fr [NC,R=301,L]
RewriteRule ^(.*)$ http://newdomain.com/$1 [R=301,L]

.htaccess redirect http to https

I have an old url (www1.test.net) and I would like to redirect it to https://www1.test.net
I have implemented and installed our SSL certificate on my site.
This is my old file .htaccess:
RewriteEngine On
RewriteRule !\.(js|gif|jpg|png|css|txt)$ public/index.php [L]
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ public/$1 [L]
How can I configure my .htaccess file so that url auto redirect to https?
Thanks!
I use the following to successfully redirect all pages of my domain from http to https:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Note this will redirect using the 301 'permanently moved' redirect, which will help transfer your SEO rankings.
To redirect using the 302 'temporarily moved' change [R=302,L]
Update 2016
As this answer receives some attention, I want to hint to a more recommended way on doing this using Virtual Hosts: Apache: Redirect SSL
<VirtualHost *:80>
ServerName mysite.example.com
Redirect permanent / https://mysite.example.com/
</VirtualHost>
<VirtualHost _default_:443>
ServerName mysite.example.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
# etc...
</VirtualHost>
Old answer, hacky thing
given that your ssl-port is not set to 80, this will work:
RewriteEngine on
# force ssl
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
Note that this should be your first rewrite rule.
Edit: This code does the following. The RewriteCond(ition) checks wether the ServerPort of the request is 80 (which is the default http-port, if you specified another port, you would have to adjust the condition to it). If so, we match the whole url (.*) and redirect it to a https-url. %{SERVER_NAME} may be replaced with a specific url, but this way you don't have to alter the code for other projects. %{REQUEST_URI} is the portion of the url after the TLD (top-level-domain), so you will be redirected to where you came from, but as https.
This is the best for www and for HTTPS, for proxy and no proxy users.
RewriteEngine On
### WWW & HTTPS
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### WWW & HTTPS
I force the https with following code:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Add this code at the end of your .htaccess file
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
In cases where the HTTPS/SSL connection is ended at the load balancer and all traffic is sent to instances on port 80, the following rule works to redirect non-secure traffic.
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Ensure the mod_rewrite module is loaded.
Searching for the best way to redirect, i've found this (coming from html5boilerplate) :
# ----------------------------------------------------------------------
# | HTTP Strict Transport Security (HSTS) |
# ----------------------------------------------------------------------
# Force client-side SSL redirection.
#
# If a user types `example.com` in their browser, even if the server
# redirects them to the secure version of the website, that still leaves
# a window of opportunity (the initial HTTP connection) for an attacker
# to downgrade or redirect the request.
#
# The following header ensures that browser will ONLY connect to your
# server via HTTPS, regardless of what the users type in the browser's
# address bar.
#
# (!) Remove the `includeSubDomains` optional directive if the website's
# subdomains are not using HTTPS.
#
# http://www.html5rocks.com/en/tutorials/security/transport-layer-security/
# https://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14#section-6.1
# http://blogs.msdn.com/b/ieinternals/archive/2014/08/18/hsts-strict-transport-security-attacks-mitigations-deployment-https.aspx
Header set Strict-Transport-Security "max-age=16070400; includeSubDomains"
Maybe it will help someone in 2017 ! :)
Insert this code in your .htaccess file. And it should work
RewriteCond %{HTTP_HOST} yourDomainName\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourDomainName.com/$1 [R,L]
This makes sure that redirects work for all combinations of intransparent proxies.
This includes the case client <http> proxy <https> webserver.
# behind proxy
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^http$
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
# plain
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^$
RewriteCond %{REQUEST_SCHEME} ^http$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
I had a problem with redirection also. I tried everything that was proposed on Stackoverflow. The one case I found by myself is:
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP:SSL} !=1 [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Adding the following to the top of the .htaccess
RewriteEngine On
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
This is what ended up working for me
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
Forcing HTTPS with the .htaccess File
==> Redirect All Web Traffic :-
To force all web traffic to use HTTPS, insert the following lines of code in the .htaccess file in your website’s root folder.
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
==> Redirect Only Specified Domain :-
To force a specific domain to use HTTPS, use the following lines of code in the .htaccess file in your website’s root folder:
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
If this doesn’t work, try removing the first two lines.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
Make sure to replace example.com with the domain name you’re trying
force to https. Additionally, you need to replace www.example.com with
your actual domain name.
==> Redirect Specified Folder :-
If you want to force SSL on a specific folder, insert the code below into a .htaccess file placed in that specific folder:
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$ https://www.example.com/folder/$1 [R=301,L]
Make sure you change the folder reference to the actual folder name.
Then be sure to replace www.example.com/folder with your actual domain
name and folder you want to force the SSL on.
Replace your domain with domainname.com , it's working with me .
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domainname.com/$1 [R,L]

apache redirect from non www to www

I have a website that doesn't seem to redirect from non-www to www.
My Apache configuration is as follows:
RewriteEngine On
### re-direct to www
RewriteCond %{http_host} !^www.example.com [nc]
RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc]
What am I missing?
Using the rewrite engine is a pretty heavyweight way to solve this problem. Here is a simpler solution:
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
# real server configuration
</VirtualHost>
And then you'll have another <VirtualHost> section with ServerName www.example.com for your real server configuration. Apache automatically preserves anything after the / when using the Redirect directive, which is a common misconception about why this method won't work (when in fact it does).
http://example.com/subdir/?lold=13666 => http://www.example.com/subdir/?lold=13666
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
<VirtualHost *:80>
ServerAlias example.com
RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>
To remove www from your URL website use this code in your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1$1 [R=301,L]
To force www in your website URL use this code on .htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^YourSite.com$
RewriteRule ^(.*)$ http://www.yourSite.com/$1 [R=301]
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule ^(([^/]+/)*[^./]+)$ /$1.html [R=301,L]
Where YourSite.com must be replaced with your URL.
<VirtualHost *:80>
DocumentRoot "what/ever/root/to/source"
ServerName www.example.com
<Directory "what/ever/root/to/source">
Options FollowSymLinks MultiViews Includes ExecCGI
AllowOverride All
Order allow,deny
allow from all
<What Ever Rules You Need.>
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerName example.com
ServerAlias *.example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
This is what happens with the code above. The first virtual host block checks if the request is www.example.com and runs your website in that directory.
Failing which, it comes to the second virtual host section. Here anything other than www.example.com is redirected to www.example.com.
The order here matters. If you add the second virtualhost directive first, it will cause a redirect loop.
This solution will redirect any request to your domain, to www.yourdomain.com.
Cheers!
This is similar to many of the other suggestions with a couple enhancements:
No need to hardcode the domain (works with vhosts that accept multiple domains or between environments)
Preserves the scheme (http/https) and ignores the effects of previous %{REQUEST_URI} rules.
The path portion not affected by previous RewriteRules like %{REQUEST_URI} is.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ %{REQUEST_SCHEME}://www.%{HTTP_HOST}/$1 [R=301,L]
Redirection code for both non-www => www and opposite www => non-www. No hardcoding domains and schemes in .htaccess file. So origin domain and http/https version will be preserved.
APACHE 2.4 AND NEWER
NON-WWW => WWW:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ %{REQUEST_SCHEME}://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
WWW => NON-WWW:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ %{REQUEST_SCHEME}://%1%{REQUEST_URI} [R=301,L]
Note: not working on Apache 2.2 where %{REQUEST_SCHEME} is not available. For compatibility with Apache 2.2 use code below or replace %{REQUEST_SCHEME} with fixed http/https.
APACHE 2.2 AND NEWER
NON-WWW => WWW:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
... or shorter version ...
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|offs
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
WWW => NON-WWW:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
... shorter version not possible because %N is available only from last RewriteCond ...
RewriteCond %{HTTP_HOST} ^!example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
This starts with the HTTP_HOST variable, which contains just the domain name portion of the incoming URL (example.com). Assuming the domain name does not contain a www. and matches your domain name exactly, then the RewriteRule comes into play. The pattern ^(.*)$ will match everything in the REQUEST_URI, which is the resource requested in the HTTP request (foo/blah/index.html). It stores this in a back reference, which is then used to rewrite the URL with the new domain name (one that starts with www).
[NC] indicates case-insensitive pattern matching, [R=301] indicates an external redirect using code 301 (resource moved permanently), and [L] stops all further rewriting, and redirects immediately.
If you are using Apache 2.4 ,without the need to enable the rewrite apache module you can use something like this:
# non-www to www
<If "%{HTTP_HOST} = 'domain.com'">
Redirect 301 "/" "http://www.domain.com/"
</If>
I ran this...
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.*$ [NC]
RewriteRule ^/.+www\/(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
I need this to be universal for 25+ domains on our new server, so this directive is in my virtual.conf file in a <Directory> tag. (dir is parent to all docroots)
I had to do a bit of a hack on the rewrite rule though, as the full docroot was being carried through on the pattern match, despite what http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html says about it only being stuff after the host and port.
Redirect domain.tld to www.
The following lines can be added either in Apache directives or in .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Other sudomains are still working.
No need to adjust the lines. just copy/paste them at the right place.
Don't forget to apply the apache changes if you modify the vhost.
(based on the default Drupal7 .htaccess but should work in many cases)
<VirtualHost *:80>
ServerAlias example.com
RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>
This will redirect not only the domain name but also the inner
pages.like...
example.com/abcd.html ==> www.example.com/abcd.html example.com/ab/cd.html?ef=gh ==> www.example.com/ab/cd.html?ef=gh
This is simple!
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Try this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*) http://www.example.com$1 [R=301]
Do not always use Redirect permanent (or why it may cause issues in future)
If there is a chance that you will add subdomains later, do not use redirect permanent.
Because if a client has used a subdomain that wasn't registred as VirtualHost he may also never reach this subdomain even when it is registred later.
redirect permanent sends an HTTP 301 Moved Permanently to the client (browser) and a lot of them cache this response for ever (until cache is cleared [manually]). So using that subdomain will always autoredirect to www.*** without requesting the server again.
see How long do browsers cache HTTP 301s?
So just use Redirect
<VirtualHost *:80>
ServerName example.com
Redirect / http://www.example.com/
</VirtualHost>
Apache.org - When not to use mod_rewrite
Apache.org - Canonical Hostnames
To 301 redirect all requests made directly to the domain to www you can use:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^([^.]+\.[^.]+){2,}$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
The benefit of this is that this will work if you have any valid subdomains, e.g.
example.com REDIRECTED TO www.example.com
foo.example.com NO REDIRECT
bar.example.com NO REDIRECT
RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]
check this perfect work
-If you host multiple domain names (Optional)
-If all those domain names are using https (as they should)
-if you want all those domain names to use www dot domainName
This will avoid doble redirection (http://non www to http://www and then to https://www)
<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(.*)$ https://www.%1$1 [R=301,L]
</VirtualHost>
And
<VirtualHost *:443>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}$1 [R=301,L]
</VirtualHost>
You should change the redirection code 301 to the most convenient one
If you want to load only the https version of www, use the below configurations in apache virtual host file. all these can have in a single file.
redirecting all http to https of www:
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
Redirect permanent / https://www.example.com/
</VirtualHost>
redirecting https non-www to https www:
<VirtualHost *:443>
ServerName example.com
Redirect permanent / https://www.example.com/
</VirtualHost>
real server configuration
<VirtualHost *:443>
ServerAdmin hostmaster#example.com
DocumentRoot "/path/to/your/sites/.htaccess-file-folder"
SetEnv APPLICATION_ENV "production"
<Directory "/path/to/your/sites/.htaccess-file-folder">
Options Indexes FollowSymLinks
DirectoryIndex index.php index.html
AllowOverride All
Order allow,deny
Allow from all
</Directory>
ServerName www.example.com
SSLEngine ON
SSLCertificateFile "/path/to/your/example.cert.pem"
SSLCertificateKeyFile "/path/to/your/example.key.pem"
ErrorLog /path/to/your/example.com-error.log
CustomLog /path/to/your/example.com-access.log combined
#Your other configurations if you have
</VirtualHost>
If using the above solution of two <VirtualHost *:80> blocks with different ServerNames...
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
</VirtualHost>
... then you must set NameVirtualHost On as well.
If you don't do this, Apache doesn't allow itself to use the different ServerNames to distinguish the blocks, so you get this error message:
[warn] _default_ VirtualHost overlap on port 80, the first has precedence
...and either no redirection happens, or you have an infinite redirection loop, depending on which block you put first.
I've just have a same problem.
But solved with this
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
This rule redirecting non-www to www.
And this rule to redirecting www to non-www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^my-domain\.com$ [NC]
RewriteRule ^(.*)$ http://my-domain.com/$1 [R=301,L]
Refer from http://dense13.com/blog/2008/02/27/redirecting-non-www-to-www-with-htaccess/
I had a similar task on a WP Multisite, where the redirection rule had to be generic (for any given domain I'd add to the network). I solved first adding a wildcard to the domain (parked domain). Note the . after .com.
CNAME * domain.com.
And then I added the following lines to the .htaccess file at the root of my multisite. I guess it'd work for any site.
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
Hopefully this will help.
ps. If you'd like to redirect from not www to www, change the last line into
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
This works for me:
RewriteCond %{HTTP_HOST} ^(?!www.domain.com).*$ [NC]
RewriteRule ^(.*)$ http://www.domain.com$1 [R=301,L]
I use the look-ahead pattern (?!www.domain.com) to exclude the www subdomain when redirecting all domains to the www subdomain in order to avoid an infinite redirect loop in Apache.
The code I use is:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
This is my own site's configuration, and works like a charm.
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAdmin admin#domain.com
ServerName www.domain.com
ServerAlias domain.com
DocumentRoot /var/www/html/domain
<Directory /var/www/html/domain/>
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# Redirect non-www to www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/domain.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/domain.com/privkey.pem
</VirtualHost>
</IfModule>
I found it easier (and more usefull) to use ServerAlias when using multiple vhosts.
<VirtualHost x.x.x.x:80>
ServerName www.example.com
ServerAlias example.com
....
</VirtualHost>
This also works with https vhosts.